Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84090433ab | ||
|
|
77d96cd4a4 | ||
|
|
d3e33b10f4 | ||
|
|
3214e4f782 | ||
|
|
e809129ae9 | ||
|
|
631a501c5c | ||
|
|
ab77900dac | ||
|
|
09d24f5022 | ||
|
|
4536a48e40 | ||
|
|
ea1249429a | ||
|
|
d2f1a8f6f4 | ||
|
|
be039dd92b | ||
|
|
2888ff2c28 | ||
|
|
c53eeefcf6 | ||
|
|
f214fccc49 | ||
|
|
63717f5eb9 | ||
|
|
7f15bc10d1 | ||
|
|
d3bcc61609 | ||
|
|
55e3ab02aa | ||
|
|
bae0da42d2 | ||
|
|
15369a016d | ||
|
|
5917942fe3 | ||
|
|
87b896fc2f | ||
|
|
6785c8a6f4 |
No files matched your search
@@ -31,4 +31,3 @@ CLAUDE.md
|
||||
|
||||
/mobile.mov
|
||||
.gstack/
|
||||
.playwright-mcp/
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,240 +1,120 @@
|
||||
"""협상카드 전술 — "스크립트에 꽂힌 변수가 곧 전술" 계층.
|
||||
"""협상카드 전술 레지스트리 — "멘트 카드 → 전술 카드" 승격 (가격 행동 실행 계층).
|
||||
|
||||
카드 멘트가 제시하는 가격({target_price}·{middle_price} 등)을 파싱해 시스템 상태로 실행한다:
|
||||
카드가 제안가를 제시하면 pending_counter_price 로 적재되고, 협력사가 수락하면 그 가격으로 타결된다.
|
||||
카드 멘트에 이미 설계된 카운터 가격 제시({target_price}·{middle_price} 등)를 시스템 상태로
|
||||
실행한다: 카드가 카운터가를 제시하면 pending_counter_price 로 적재되고, 협력사가 수락하면
|
||||
그 가격으로 즉시 타결된다(기존 wild_card_1pct 의 offer_1pct 패턴을 일반화).
|
||||
|
||||
세 계층으로 나뉜다.
|
||||
1) 스크립트 파싱 — 이 카드가 부를 금액이 무엇인지 (parse_offer_variable)
|
||||
2) 변수 정의 — 그 금액을 지금 쓸 수 있는지 (OFFER_VARIABLES 의 계산식 + 유효조건)
|
||||
3) tactic JSONB — 문장으로 알 수 없는 운영 규칙 (min_round·closing)
|
||||
원칙:
|
||||
- 구매자(갑) 대리이므로 카운터는 항상 min(counter, target_price) 클램프 — 목표가 초과 제시 금지.
|
||||
- 협력사 제시가가 이미 카운터 이하면 카운터가 무의미 → None(HOLD 강등, 순수 설득).
|
||||
- 미등록 카드번호(테넌트 데모 NGC-B*, 회사 커스텀 COMP-* 등)는 HOLD 폴백 → 기존 동작 그대로.
|
||||
|
||||
유효 조건은 카드가 아니라 '변수'에 붙인다 — 금액이 성립하는지는 계산식의 성질이지 카드의
|
||||
성질이 아니다. 새 변수는 OFFER_VARIABLES 에 한 줄 추가하면 코드 분기 없이 끝난다.
|
||||
전술 정본은 이 코드 레지스트리다(v1). negodata 카드 편집은 멘트만 담당하고, 전술을 negodata
|
||||
에서 편집할 필요가 생기면 v2 에서 card.nego_cards 컬럼로 승격해 "DB 우선, 코드 폴백"으로 바꾼다.
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
# 제안가 변수 — 우리가 새로 부르는 금액. 값은 (계산식, 재료 설명).
|
||||
# 여기 없는 치환 변수({prev_partner_price}·{internet_lowest_price} 등)는 읽어주기 전용이라
|
||||
# 제안가가 되지 않는다 — 과거값·외부값을 협력사에게 "수락하라"고 내밀 수 없기 때문.
|
||||
OFFER_VARIABLES: Dict[str, Callable[[float, float, float, float], Optional[float]]] = {
|
||||
# (target, anchor, price, prev_customer) -> 제안가 | None(재료 없음)
|
||||
"target_price": lambda target, anchor, price, prev: target,
|
||||
"anchoring_price": lambda target, anchor, price, prev: anchor or None,
|
||||
# negodata 카드 에디터 칩 표기(variables.ts) — DB 시드 표기(anchoring_price)와 같은 값의 별칭.
|
||||
"anchor_price": lambda target, anchor, price, prev: anchor or None,
|
||||
"target_mid_price": lambda target, anchor, price, prev: (anchor + target) / 2 if anchor else None,
|
||||
"middle_price": lambda target, anchor, price, prev: (prev + price) / 2 if prev else None,
|
||||
}
|
||||
|
||||
_TOKEN_RE = re.compile(r"\{([a-z_]+)\}")
|
||||
|
||||
# 절충 계열 변수 — 양측 사이/우리 두 값 사이의 중간을 부르는 카드. 목표가 이상이면 미발동한다.
|
||||
_MID_VARIABLES = ("middle_price", "target_mid_price")
|
||||
from enum import Enum
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
# 세션 데이터에 따라 값이 없을 수 있는 읽기 전용 변수 → 그 값을 담는 컨텍스트 키.
|
||||
# 스크립트가 이런 변수를 인용하면 값이 있을 때만 카드가 나간다 — 없는데 나가면 협력사 채팅에
|
||||
# {internet_lowest_price} 토큰이 원형 노출된다(vars_for 가 미수집이면 키를 안 만드는 것과 짝).
|
||||
# 견적 생성 화면 게이팅(useCardGating)이 1차 방어, 여기가 2차(런타임) 방어다.
|
||||
_CONTEXT_REQUIRED_VARIABLES = {
|
||||
"internet_lowest_price": "internet_lowest_price",
|
||||
"internet_min_price": "internet_lowest_price",
|
||||
}
|
||||
class PriceAction(str, Enum):
|
||||
HOLD = "hold" # 카운터 없음 — 재제안 요구(순수 설득, 기존 동작)
|
||||
COUNTER_TARGET = "counter_target" # 목표가 제시
|
||||
COUNTER_ANCHOR = "counter_anchor" # 앵커가 제시 (예산 상한 프레이밍)
|
||||
COUNTER_TARGET_MID = "counter_target_mid" # (anchor+target)/2 — 시드 {target_mid_price}
|
||||
COUNTER_MID = "counter_mid" # (갑 직전 포지션+협력사 제시가)/2 — 시드 {middle_price}
|
||||
ONE_PCT = "one_pct" # 제시가 1% 인하 (기존 offer_1pct)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CardSpec:
|
||||
"""카드 1장의 전술. 스크립트 파싱 결과 + tactic JSONB 를 합친 값.
|
||||
class TacticSpec:
|
||||
"""카드 1장의 전술 명세.
|
||||
|
||||
offer_variable: 이 카드가 제시할 금액의 변수명. None 이면 순수 설득 카드(HOLD).
|
||||
min_round: 발동 가능 최소 라운드(협력사 가격 입력 횟수 기준).
|
||||
closing: 종결 국면 전용 — 라운드 상한·카드 소진 시의 마지막 한 방으로만 쓴다.
|
||||
requires: 스크립트가 인용한 세션-의존 변수의 컨텍스트 키 — 값이 없으면 미발동(토큰 노출 방지).
|
||||
max_price_ratio: input_price ≤ anchor×ratio 일 때만 발동 (None=무제한).
|
||||
closing: 종결 국면(라운드 만료·카드 소진) 우선 전술.
|
||||
"""
|
||||
|
||||
offer_variable: Optional[str] = None
|
||||
price_action: PriceAction = PriceAction.HOLD
|
||||
min_round: int = 1
|
||||
max_price_ratio: Optional[float] = None
|
||||
closing: bool = False
|
||||
requires: tuple = ()
|
||||
|
||||
|
||||
HOLD = CardSpec() # 스펙을 못 찾은 카드(테넌트 데모·회사 커스텀)의 폴백 — 기존 동작(설득만) 유지
|
||||
_DEFAULT = TacticSpec() # HOLD — 미등록 카드 폴백
|
||||
|
||||
# 카드번호 → 전술. 시드(init-data.sql) 멘트의 가격 변수와 1:1 정합.
|
||||
# NGC-001~006: 순수 설득(경쟁 압박/승인 핑계/관계/명분/공정성/TCO) — 가격 변수 없음.
|
||||
# NGC-008: {internet_lowest_price} 인용이나 데이터 소스 미보유 → v1 HOLD (소스 확보 시 승격).
|
||||
_TACTICS: Dict[str, TacticSpec] = {
|
||||
"NGC-007": TacticSpec(PriceAction.COUNTER_ANCHOR), # 예산 상한 안내
|
||||
"NGC-009": TacticSpec(PriceAction.COUNTER_TARGET), # 조건부 가격 조정
|
||||
"NGC-010": TacticSpec(PriceAction.COUNTER_TARGET), # 향후 거래 연계
|
||||
"NGC-011": TacticSpec(PriceAction.COUNTER_TARGET), # 양보 가치 강조
|
||||
"WC-01": TacticSpec(PriceAction.COUNTER_TARGET, min_round=1), # 목표가 선제안
|
||||
"WC-02": TacticSpec(PriceAction.COUNTER_TARGET_MID), # 역제안가 제시
|
||||
"WC-03": TacticSpec(PriceAction.COUNTER_TARGET, closing=True), # 최종 통보(최후통첩)
|
||||
"WC-04": TacticSpec(PriceAction.COUNTER_TARGET, min_round=2), # 단계적 인하 제안
|
||||
"WC-05": TacticSpec(PriceAction.COUNTER_MID, closing=True), # 중간값 절충(종결)
|
||||
}
|
||||
|
||||
|
||||
def settle_ceiling(context: Dict[str, Any]) -> float:
|
||||
"""이 협상에서 받아줄 수 있는 최고가 — 타결 판정선이자 카드 제안가의 상한.
|
||||
def tactic_for(card_number: Optional[str]) -> TacticSpec:
|
||||
"""카드번호의 전술. 미등록/None 은 HOLD(기존 동작)."""
|
||||
return _TACTICS.get(str(card_number), _DEFAULT) if card_number else _DEFAULT
|
||||
|
||||
견적 생성 시 세션에 박제한 done_ceiling_price(= 목표가 × (1 + 타결상한율)) — 목표가를 조금
|
||||
넘더라도 기존 단가보다 인하됐으면 타결시키기 위한 값. 박제가 없으면 목표가로 폴백한다.
|
||||
|
||||
def tactic_available(spec: TacticSpec, context: Dict[str, Any]) -> bool:
|
||||
"""발동 조건 평가 — action space 마스킹용. HOLD(설득)는 언제나 가능."""
|
||||
if spec.price_action is PriceAction.HOLD:
|
||||
return True
|
||||
rnd = int(context.get("round") or 0)
|
||||
if rnd < spec.min_round:
|
||||
return False
|
||||
if spec.max_price_ratio is not None:
|
||||
price = float(context.get("input_price") or 0)
|
||||
anchor = float(context.get("anchor_price") or 0)
|
||||
if anchor > 0 and price > anchor * spec.max_price_ratio:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def compute_counter(spec: TacticSpec, context: Dict[str, Any]) -> Optional[int]:
|
||||
"""전술의 카운터 제시가 계산 (결정론).
|
||||
|
||||
- 항상 min(counter, target) 클램프 — 구매자는 목표가 초과로 제시하지 않는다.
|
||||
- counter ≥ 협력사 제시가(input_price)면 카운터가 무의미(이미 더 싸게 제시받음) → None.
|
||||
- 필요한 컨텍스트(target/anchor/제시가)가 없으면 None → 호출부가 HOLD 로 강등.
|
||||
"""
|
||||
return float(context.get("done_ceiling_price") or context.get("target_price") or 0)
|
||||
|
||||
|
||||
def parse_offer_variable(script: Optional[str]) -> Optional[str]:
|
||||
"""스크립트가 제시하는 제안가 변수. 없으면 None(설득 카드).
|
||||
|
||||
변수가 여럿이면 마지막에 등장하는 것이 제안가다 — 카드 문장은 배경을 먼저 깔고 실제 제안을
|
||||
마지막에 하기 때문이다.
|
||||
"""
|
||||
found = [m.group(1) for m in _TOKEN_RE.finditer(script or "") if m.group(1) in OFFER_VARIABLES]
|
||||
return found[-1] if found else None
|
||||
|
||||
|
||||
def build_card_spec(script: Optional[str], tactic: Optional[dict] = None) -> CardSpec:
|
||||
"""스크립트 + tactic JSONB → CardSpec. tactic 이 비어 있으면 전부 기본값."""
|
||||
t = tactic or {}
|
||||
cited = {m.group(1) for m in _TOKEN_RE.finditer(script or "")}
|
||||
return CardSpec(
|
||||
# 파싱이 정본 카드 전부를 맞히므로 offer_variable 은 예외 카드용 override 로만 둔다.
|
||||
offer_variable=t.get("offer_variable") or parse_offer_variable(script),
|
||||
min_round=int(t.get("min_round") or 1),
|
||||
closing=bool(t.get("closing")),
|
||||
requires=tuple(sorted({_CONTEXT_REQUIRED_VARIABLES[v] for v in cited if v in _CONTEXT_REQUIRED_VARIABLES})),
|
||||
)
|
||||
|
||||
|
||||
def spec_from_context(context: Dict[str, Any], number: Optional[str]) -> CardSpec:
|
||||
"""세션 컨텍스트에 적재된 카드 스펙(card_specs)에서 꺼낸다. 없으면 HOLD 폴백.
|
||||
|
||||
스펙은 협상 시작 시 1회 적재된다(negotiation_context_loader) — 진행 중인 협상은
|
||||
카드 멘트가 도중에 바뀌어도 시작 시점 전술로 끝까지 간다.
|
||||
"""
|
||||
if not number:
|
||||
return HOLD
|
||||
raw = (context.get("card_specs") or {}).get(str(number))
|
||||
if not raw:
|
||||
return HOLD
|
||||
return CardSpec(
|
||||
offer_variable=raw.get("offer_variable"),
|
||||
min_round=int(raw.get("min_round") or 1),
|
||||
closing=bool(raw.get("closing")),
|
||||
requires=tuple(raw.get("requires") or ()),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Offer:
|
||||
"""확정된 제안 한 건 — 금액과 그 금액을 만든 재료를 함께 들고 다닌다.
|
||||
|
||||
멘트 치환이 재료를 다시 계산하지 않게 하기 위한 것 — 재계산하면 그 사이 갱신된
|
||||
prev_customer 를 읽어 문장이 자기모순이 된다.
|
||||
"""
|
||||
|
||||
price: int # 협력사에게 제시할 금액(수락 시 타결가)
|
||||
variable: str # 이 금액을 만든 멘트 변수
|
||||
prev_customer: int # 계산에 쓴 당사 직전 제안
|
||||
prev_partner: int # 계산에 쓴 협력사 제시가
|
||||
|
||||
|
||||
def record_offer(context: Dict[str, Any], offer: Offer) -> None:
|
||||
"""확정 제안을 세션에 기록한다 — 수락 판정용 금액과 멘트 치환용 재료를 한 자리에서 쓴다.
|
||||
|
||||
두 키를 항상 함께 써야 표시가와 타결가가 갈라지지 않으므로 기록 지점을 여기 하나로 묶는다.
|
||||
"""
|
||||
context["pending_counter_price"] = offer.price
|
||||
context["pending_offer"] = {
|
||||
"price": offer.price, "variable": offer.variable,
|
||||
"prev_customer": offer.prev_customer, "prev_partner": offer.prev_partner,
|
||||
}
|
||||
context["prev_customer_price"] = offer.price # 갑의 최신 포지션 — 다음 라운드 계산·역행 금지 기준
|
||||
|
||||
|
||||
def compute_offer_detail(spec: CardSpec, context: Dict[str, Any]) -> Optional[Offer]:
|
||||
"""카드가 제시할 금액 + 그 계산에 쓴 재료. 쓸 수 없는 상황이면 None."""
|
||||
price = int(float(context.get("input_price") or 0))
|
||||
prev_customer = int(float(context.get("prev_customer_price") or context.get("anchor_price") or 0))
|
||||
value = compute_offer(spec, context)
|
||||
if value is None:
|
||||
action = spec.price_action
|
||||
if action is PriceAction.HOLD:
|
||||
return None
|
||||
return Offer(price=value, variable=spec.offer_variable or "", prev_customer=prev_customer, prev_partner=price)
|
||||
|
||||
|
||||
def compute_offer(spec: CardSpec, context: Dict[str, Any]) -> Optional[int]:
|
||||
"""카드가 제시할 금액. 쓸 수 없는 상황이면 None → 호출부가 카드를 건너뛴다.
|
||||
|
||||
변수 공통 유효조건 (전부 만족해야 발동):
|
||||
· 값 ≤ 타결 상한가 — 받아줄 수 없는 금액은 부르지 않는다. 넘으면 깎지 않고 미발동
|
||||
· 값 < 협력사 제시가 — 이미 더 싸게 받았는데 더 비싼 값을 부를 이유가 없다
|
||||
· 값 ≥ 당사 직전 제안 — 역행 금지. 제안 시퀀스는 앵커→…→목표가로 단조 수렴해야 한다
|
||||
"""
|
||||
variable = spec.offer_variable
|
||||
if not variable:
|
||||
return None # 설득 카드 — 제시할 금액 없음
|
||||
calc = OFFER_VARIABLES.get(variable)
|
||||
if calc is None:
|
||||
return None # 미등록 변수(오타·구버전 카드)
|
||||
target = float(context.get("target_price") or 0)
|
||||
anchor = float(context.get("anchor_price") or 0)
|
||||
price = float(context.get("input_price") or 0)
|
||||
# 갑의 직전 포지션. 첫 카운터 전에는 앵커가 갑의 포지션이다.
|
||||
prev_customer = float(context.get("prev_customer_price") or anchor or 0)
|
||||
if target <= 0 or price <= 0:
|
||||
return None # 목표가·제시가 없이는 어떤 변수도 판정 불가
|
||||
|
||||
value = calc(target, anchor, price, prev_customer)
|
||||
if not value or value <= 0:
|
||||
return None # 재료 부족(앵커 미박제·직전 제안 없음)
|
||||
if value > settle_ceiling(context):
|
||||
return None # 타결 상한 초과 — 받아줄 수 없는 금액이라 지금 못 쓴다
|
||||
if variable in _MID_VARIABLES and value >= target:
|
||||
# 절충 계열은 목표가 미만일 때만 의미가 있다. 목표가 이상이면 "절반씩 나누자"면서 목표가를
|
||||
# 부르는 꼴이라 미발동 — 목표가 제시는 목표가 카드(최후통첩)가 할 일이다.
|
||||
return None
|
||||
if variable in ("target_price", "anchoring_price", "anchor_price"):
|
||||
# 원값 인용 변수 — 멘트엔 {target_price} 등 저장 원값이 그대로 나가므로, 반올림하면
|
||||
# 표시가≠타결가 미스매치가 난다(목표가 7652 멘트 → 7650 타결). 저장값 그대로 제시.
|
||||
offer = int(value)
|
||||
|
||||
if action is PriceAction.COUNTER_TARGET:
|
||||
counter = target
|
||||
elif action is PriceAction.COUNTER_ANCHOR:
|
||||
counter = anchor
|
||||
elif action is PriceAction.COUNTER_TARGET_MID:
|
||||
counter = (anchor + target) / 2 if anchor > 0 else target
|
||||
elif action is PriceAction.COUNTER_MID:
|
||||
# 갑의 직전 포지션(직전 카운터). 첫 카운터 전에는 앵커가 갑의 포지션이다.
|
||||
prev_customer = float(context.get("prev_customer_price") or anchor or target)
|
||||
counter = (prev_customer + price) / 2
|
||||
elif action is PriceAction.ONE_PCT:
|
||||
counter = price * 0.99
|
||||
else:
|
||||
offer = int(value / 10 + 0.5) * 10 # 파생가(절충·중간) 10원 반올림 — 앵커·목표가 산정과 표기 통일
|
||||
if offer >= price:
|
||||
return None # 제시가가 이미 그 값 이하 → 부를 이유 없음
|
||||
if prev_customer and offer < prev_customer:
|
||||
return None # 역행 금지 — 한번 부른 금액 아래로 되돌아가지 않는다(같은 금액 재제시는 허용)
|
||||
return offer
|
||||
return None
|
||||
|
||||
|
||||
def available(spec: CardSpec, context: Dict[str, Any], *, closing_phase: bool = False) -> bool:
|
||||
"""지금 이 카드를 꺼낼 수 있는지 — 금액과 무관한 조건들.
|
||||
|
||||
· 이미 쓴 카드는 다시 안 나간다(전 카드 공통 규칙 — 협상카드/와일드카드 구분 없음)
|
||||
· 종결 전용 카드는 종결 국면에서만, 종결 국면에선 종결 전용 카드만
|
||||
· min_round 미만이면 아직 이르다
|
||||
· 스크립트가 인용한 세션-의존 변수(인터넷 최저가 등)가 결측이면 미발동 — 토큰 원형 노출 방지
|
||||
"""
|
||||
if spec.closing != closing_phase:
|
||||
return False
|
||||
if int(context.get("round") or 0) < spec.min_round:
|
||||
return False
|
||||
return all(context.get(key) for key in spec.requires)
|
||||
|
||||
|
||||
def playable(spec: CardSpec, context: Dict[str, Any], *, closing_phase: bool = False) -> bool:
|
||||
"""이 카드를 지금 실제로 플레이할 수 있는지 — available + (금액 카드는) 제안가 유효까지.
|
||||
|
||||
금액을 인용하는 카드(offer_variable 있음)는 그 금액을 못 부르는 상황이면 설득 폴백으로도
|
||||
내보내지 않는다 — 멘트에 무효한 금액(직전 제안보다 낮은 앵커, 제시가보다 높은 목표가)이
|
||||
글자로 박혀 나가 역행/모순 서사가 되기 때문. 설득 카드는 금액이 없으니 무관.
|
||||
"""
|
||||
if not available(spec, context, closing_phase=closing_phase):
|
||||
return False
|
||||
if not spec.offer_variable:
|
||||
return True
|
||||
return compute_offer(spec, context) is not None
|
||||
|
||||
|
||||
def is_played(context: Dict[str, Any], number: Optional[str]) -> bool:
|
||||
"""이 카드를 이 협상에서 이미 썼는지. 와일드 진입·종결·협상카드가 같은 이력을 본다."""
|
||||
return bool(number) and str(number) in (context.get("played_card_numbers") or [])
|
||||
|
||||
|
||||
def mark_played(context: Dict[str, Any], number: Optional[str]) -> None:
|
||||
"""카드를 실제로 내보낸 시점에 이력에 남긴다(노출되지 않은 후보는 남기지 않는다)."""
|
||||
if not number:
|
||||
return
|
||||
played = list(context.get("played_card_numbers") or [])
|
||||
if str(number) not in played:
|
||||
played.append(str(number))
|
||||
context["played_card_numbers"] = played
|
||||
if counter <= 0:
|
||||
return None
|
||||
counter = min(counter, target) # 목표가 초과 제시 금지 (가드레일)
|
||||
counter_i = int(counter / 10 + 0.5) * 10 # 10원 단위 반올림 — 앵커가·목표가 산정과 표기 통일(IMK 요청)
|
||||
if counter_i >= price:
|
||||
return None # 제시가가 이미 카운터 이하 → 카운터 무의미
|
||||
return counter_i
|
||||
@@ -23,7 +23,6 @@ _SESSIONS = table(
|
||||
"sessions",
|
||||
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
|
||||
column("qt_type"), column("target_price"), column("anchoring_price"),
|
||||
column("done_ceiling_price"), # 타결 상한가 — 견적 생성 시 박제(목표가×(1+타결상한율))
|
||||
column("qt_setting_id"),
|
||||
column("deleted"),
|
||||
schema="negotiation",
|
||||
@@ -34,32 +33,8 @@ _QUOTATION_SETTINGS = table(
|
||||
column("qt_setting_id"), column("card_count"), column("deleted"),
|
||||
schema="quotation",
|
||||
)
|
||||
_ITEMS = table("items", column("item_id"), column("name"), column("price"), column("purchase_price"),
|
||||
column("company_id"), column("internet_lowest_price"), column("deleted"), schema="partner")
|
||||
# 고객사 설정(companies.settings) — 협상 기준가로 쓸 가격 컬럼을 여기서 정한다.
|
||||
_COMPANIES = table("companies", column("company_id"), column("settings"), column("deleted"), schema="company")
|
||||
|
||||
# 협상 기준가 후보 컬럼. 어느 컬럼을 고르든 공급사 화면 호칭은 '공급가'로 고정한다 —
|
||||
# 같은 돈을 고객사는 매입가·상품 단가 등으로 부르지만 챗은 공급사가 보는 화면이라
|
||||
# 공급사 관점 용어 하나만 쓴다. 회사 용어 사전(labels)은 관리자 화면 전용.
|
||||
_BASELINE_PRICE = "price"
|
||||
_BASELINE_PURCHASE = "purchase_price"
|
||||
_SUPPLIER_PRICE_LABEL = "공급가"
|
||||
|
||||
|
||||
def _resolve_baseline(settings: dict) -> str:
|
||||
"""회사 설정 → 협상 기준가로 쓸 items 컬럼명.
|
||||
|
||||
1순위는 관리자가 회사 설정에서 고른 값(features.nego_baseline_field).
|
||||
미설정 회사는 공급가가 기본이되, 공급가를 화면에서 감췄다면 그 회사는 공급가를 관리하지
|
||||
않는다는 뜻이므로 매입가로 폴백한다 — 설정 화면이 생기기 전에 만들어진 회사를 위한 안전망."""
|
||||
chosen = (settings.get("features") or {}).get("nego_baseline_field")
|
||||
if chosen in (_BASELINE_PRICE, _BASELINE_PURCHASE):
|
||||
return chosen
|
||||
hidden = set(settings.get("hidden_fields") or [])
|
||||
if "price" in hidden and "purchase_price" not in hidden:
|
||||
return _BASELINE_PURCHASE
|
||||
return _BASELINE_PRICE
|
||||
_ITEMS = table("items", column("item_id"), column("name"), column("price"),
|
||||
column("internet_lowest_price"), column("deleted"), schema="partner")
|
||||
_SUPPLIERS = table("suppliers", column("supplier_id"), column("name"), column("total_revenue"), column("deleted"), schema="partner")
|
||||
_QUOTATIONS = table(
|
||||
"quotations",
|
||||
@@ -78,13 +53,12 @@ _VERSION_WILD_CARDS = table(
|
||||
)
|
||||
_NEGO_CARDS = table(
|
||||
"nego_cards",
|
||||
column("nego_card_id"), column("number"), column("script"), column("tactic"), column("deleted"),
|
||||
column("nego_card_id"), column("number"), column("deleted"),
|
||||
schema="card",
|
||||
)
|
||||
_WILD_CARDS = table(
|
||||
"wild_cards",
|
||||
column("wild_card_id"), column("number"), column("script"), column("tactic"), column("deleted"),
|
||||
column("available"),
|
||||
column("wild_card_id"), column("number"), column("deleted"),
|
||||
schema="card",
|
||||
)
|
||||
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
|
||||
@@ -98,16 +72,12 @@ _SUPPLIER_ITEMS = table(
|
||||
class INegoContextCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""세션 행 (qt_type, target_price, anchoring_price, done_ceiling_price, item_id, quotation_id, supplier_id). 없으면 None."""
|
||||
"""세션 행 (qt_type, target_price, anchoring_price, item_id, quotation_id, supplier_id). 없으면 None."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_item_baseline(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Tuple[int, str, dict]]:
|
||||
"""협상 기준가·그 호칭·회사 용어 사전 (가격, 호칭, labels).
|
||||
|
||||
어느 컬럼을 기준가로 쓰는지는 회사 설정(features.nego_baseline_field)이 정한다.
|
||||
labels 는 companies.settings.labels 원본 — 협상 스크립트의 용어 토큰 치환에 쓴다.
|
||||
값이 없으면 (0, 호칭, {})."""
|
||||
async def get_item_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""품목 기준가(items.price). 없으면 0."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -154,9 +124,8 @@ class INegoContextCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[tuple], list[tuple]]]:
|
||||
"""견적 version_id 에 연결된 (일반카드 행 목록, 와일드카드 행 목록). 없으면 빈 목록.
|
||||
행 = (number, script, tactic) — 스크립트 파싱 + tactic JSONB 로 카드 전술(CardSpec)을 만든다."""
|
||||
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[str], list[str]]]:
|
||||
"""견적 version_id 에 연결된 (일반카드 번호 목록, 와일드카드 번호 목록). 없으면 빈 목록."""
|
||||
pass
|
||||
|
||||
|
||||
@@ -165,7 +134,6 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
try:
|
||||
query = (
|
||||
select(_SESSIONS.c.qt_type, _SESSIONS.c.target_price, _SESSIONS.c.anchoring_price,
|
||||
_SESSIONS.c.done_ceiling_price,
|
||||
_SESSIONS.c.item_id, _SESSIONS.c.quotation_id, _SESSIONS.c.supplier_id)
|
||||
.where(_SESSIONS.c.session_id == session_id, _SESSIONS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
@@ -178,29 +146,20 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_item_baseline(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Tuple[int, str, dict]]:
|
||||
_fallback = (0, _SUPPLIER_PRICE_LABEL, {})
|
||||
async def get_item_price(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
# 상품 + 소속 고객사 설정 한 번에. 회사가 없어도(데이터 이상) 상품 행은 나오도록 outer join.
|
||||
query = (
|
||||
select(_ITEMS.c.price, _ITEMS.c.purchase_price, _COMPANIES.c.settings)
|
||||
.select_from(_ITEMS.outerjoin(_COMPANIES, _ITEMS.c.company_id == _COMPANIES.c.company_id))
|
||||
select(_ITEMS.c.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_baseline failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
return err_type, _fallback
|
||||
# 컬럼이 2개 이상이면 execute 가 행 리스트를 준다(1개일 때만 스칼라 리스트).
|
||||
price, purchase_price, settings = rows[0]
|
||||
settings = settings if isinstance(settings, dict) else {}
|
||||
labels = settings.get("labels") or {}
|
||||
field = _resolve_baseline(settings)
|
||||
value = purchase_price if field == _BASELINE_PURCHASE else price
|
||||
return ErrorType.SUCCESS, (int(value or 0), _SUPPLIER_PRICE_LABEL, labels)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_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, _fallback
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_card_count(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
try:
|
||||
@@ -330,7 +289,7 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[tuple], list[tuple]]]:
|
||||
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[str], list[str]]]:
|
||||
try:
|
||||
version_q = (
|
||||
select(_QUOTATIONS.c.version_id)
|
||||
@@ -345,7 +304,7 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
version_id = rows[0]
|
||||
|
||||
nego_q = (
|
||||
select(_NEGO_CARDS.c.number, _NEGO_CARDS.c.script, _NEGO_CARDS.c.tactic)
|
||||
select(_NEGO_CARDS.c.number)
|
||||
.select_from(
|
||||
_VERSION_NEGO_CARDS.join(
|
||||
_NEGO_CARDS,
|
||||
@@ -364,7 +323,7 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
return n_err, ([], [])
|
||||
|
||||
wild_q = (
|
||||
select(_WILD_CARDS.c.number, _WILD_CARDS.c.script, _WILD_CARDS.c.tactic)
|
||||
select(_WILD_CARDS.c.number)
|
||||
.select_from(
|
||||
_VERSION_WILD_CARDS.join(
|
||||
_WILD_CARDS,
|
||||
@@ -375,8 +334,6 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
_VERSION_WILD_CARDS.c.version_id == version_id,
|
||||
_VERSION_WILD_CARDS.c.deleted == False, # noqa: E712
|
||||
_WILD_CARDS.c.deleted == False, # noqa: E712
|
||||
# 협상 적용 여부(카드 설정 '적용 대기(수동)') — 꺼진 카드는 견적에 담겨 있어도 발동 금지
|
||||
_WILD_CARDS.c.available == True, # noqa: E712
|
||||
)
|
||||
.order_by(_VERSION_WILD_CARDS.c.created_at)
|
||||
)
|
||||
@@ -385,8 +342,8 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
return w_err, ([], [])
|
||||
|
||||
return ErrorType.SUCCESS, (
|
||||
[(str(r[0]), r[1], r[2]) for r in n_rows if r[0] is not None],
|
||||
[(str(r[0]), r[1], r[2]) for r in w_rows if r[0] is not None],
|
||||
[str(r) for r in n_rows if r is not None],
|
||||
[str(r) for r in w_rows if r is not None],
|
||||
)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
|
||||
@@ -10,16 +10,10 @@ import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from negotiation.cards.domain.tactics import (
|
||||
OFFER_VARIABLES, Offer, available, compute_offer_detail, is_played, mark_played, playable,
|
||||
record_offer, settle_ceiling, spec_from_context,
|
||||
)
|
||||
from negotiation.cards.domain.tactics import compute_counter, tactic_for
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
|
||||
MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config negotiation.max_counter_rounds)
|
||||
# 멘트에 찍히는 파생 가격 — 값이 다른 값에서 계산돼 나오는 것들(원값 인용 target/anchor 는 제외).
|
||||
_DERIVED_PRICE_VARIABLES = ("target_mid_price", "middle_price")
|
||||
|
||||
_PRICE_MODES = ("price",)
|
||||
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
|
||||
|
||||
@@ -49,39 +43,6 @@ def _parse_price(user_input: Any) -> Optional[float]:
|
||||
return price if price > 0 else None
|
||||
|
||||
|
||||
# 협상 스크립트가 쓰는 용어 토큰: {label_*} = 회사 용어(없으면 기본값).
|
||||
# 값은 negodata 용어 카탈로그(LABEL_CATALOG)의 base 와 같아야 화면·멘트 표기가 갈리지 않는다.
|
||||
_SCRIPT_LABELS = {
|
||||
"label_supplier": ("supplier", "협력사"),
|
||||
"label_target_price": ("target_price", "목표가"),
|
||||
"label_delivery_type": ("item.delivery_type", "배송 형태"),
|
||||
"label_delivery_type_1": ("delivery_type.1", "협력사배송"),
|
||||
"label_delivery_type_2": ("delivery_type.2", "지정택배배송"),
|
||||
"label_delivery_type_3": ("delivery_type.3", "픽업배송"),
|
||||
"label_product": ("item.name", "상품명"),
|
||||
}
|
||||
# 협상 기준가 호칭 — 공급사 화면 고정 용어. 회사 용어 사전(labels)을 타지 않는다(그건 관리자 화면 전용).
|
||||
# 실제 값은 loader 가 컨텍스트에 박제하고, DB 컨텍스트가 없는 데모/직접호출 경로만 이 폴백을 쓴다.
|
||||
_SUPPLIER_PRICE_LABEL = "공급가"
|
||||
# 조사 자동 보정: 토큰 뒤에 조사가 붙는 자리는 {label_supplier_를} 처럼 대표형을 적는다.
|
||||
# 회사가 바꾼 용어의 받침을 예측할 수 없어 스크립트에 조사를 고정할 수 없다("협력사를"/"공급업체을").
|
||||
_JOSA = {"은": ("은", "는"), "는": ("은", "는"), "이": ("이", "가"), "가": ("이", "가"),
|
||||
"을": ("을", "를"), "를": ("을", "를"), "과": ("과", "와"), "와": ("과", "와")}
|
||||
|
||||
|
||||
def _has_batchim(word: str) -> bool:
|
||||
last = word[-1] if word else ""
|
||||
return "가" <= last <= "힣" and (ord(last) - 0xAC00) % 28 != 0
|
||||
|
||||
|
||||
def _josa(word: str, form: str) -> str:
|
||||
"""단어 + 받침에 맞는 조사. form 은 대표형('를'·'는'·'가'·'와')."""
|
||||
pair = _JOSA.get(form)
|
||||
if not pair:
|
||||
return word
|
||||
return word + (pair[0] if _has_batchim(word) else pair[1])
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatSession:
|
||||
session_id: str
|
||||
@@ -135,9 +96,8 @@ class ChatEngine:
|
||||
if price is None:
|
||||
return self._error(session, "가격을 숫자로 입력해 주세요.")
|
||||
session.context["input_price"] = price
|
||||
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터·그 재료 폐기.
|
||||
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터 폐기.
|
||||
session.context.pop("pending_counter_price", None)
|
||||
session.context.pop("pending_offer", None)
|
||||
session.context["prev_partner_price"] = price
|
||||
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
|
||||
session.context.setdefault("first_offer_price", price)
|
||||
@@ -155,7 +115,6 @@ class ChatEngine:
|
||||
# 원 제시가 수락 종결 — 는 카운터를 버리고 기존 input_price 로 타결한다.)
|
||||
if mode in _CHOICE_MODES and nxt in _SUCCESS_STEPS:
|
||||
pending = session.context.pop("pending_counter_price", None)
|
||||
session.context.pop("pending_offer", None)
|
||||
if pending and user_input in _ACCEPT_INPUTS:
|
||||
session.context["input_price"] = float(pending)
|
||||
return self._render(session, nxt)
|
||||
@@ -210,15 +169,6 @@ class ChatEngine:
|
||||
and price <= anchor * self.rules.wildcard_entry_ratio)
|
||||
)
|
||||
)
|
||||
# 구간에 들어와도 실제로 낼 카드가 없으면(전부 종결 전용·사용됨·유효조건 미달) 이 조건은
|
||||
# 불충족으로 두고 다음 조건(우선협상·소진 판정)을 평가한다 — 여기서 매칭돼 버리면
|
||||
# 카드 소진 판정이 영영 돌지 않아, 빈 덱에서 쓴 카드를 또 꺼내는 무한 협상이 된다.
|
||||
if ok:
|
||||
probe = ChatSession(
|
||||
session_id=session.session_id, tenant_id=session.tenant_id,
|
||||
company_id=session.company_id, context=dict(ctx),
|
||||
)
|
||||
ok = self._pick_wildcard(probe) != "가격협상"
|
||||
elif cond == "check_is_supplier_type_c":
|
||||
ok = False # 공급사 유형 미보유 (PoC 단순화)
|
||||
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
|
||||
@@ -231,27 +181,13 @@ class ChatEngine:
|
||||
# ② 종결 전술까지 소진(closing_played)이면 → 최종 제시가 ≤ target 은 타결,
|
||||
# 초과는 결렬(협상실패) — "목표가 초과 타결 금지" 가드레일과 정합.
|
||||
counter_rounds = max(0, ctx.get("round", 0) - 1)
|
||||
# 담은 협상카드 중 지금 낼 수 있는 게 하나도 없으면(사용됨·발동조건 미달 — 예:
|
||||
# 시장가 인용 카드인데 최저가 결측) 장수와 무관하게 소진으로 본다 — 안 그러면
|
||||
# 선택 마스크가 전부 막힌 채 폴백이 부적합 카드를 억지로 꺼낸다(토큰 노출).
|
||||
selected = ctx.get("selected_nego_card_numbers") or []
|
||||
none_playable = bool(selected) and not any(
|
||||
not is_played(ctx, n) and playable(spec_from_context(ctx, n), ctx)
|
||||
for n in selected
|
||||
)
|
||||
exhausted = (
|
||||
counter_rounds >= self.rules.max_counter_rounds
|
||||
or (cards_total > 0 and cards_used >= cards_total)
|
||||
or none_playable
|
||||
)
|
||||
exhausted = counter_rounds >= self.rules.max_counter_rounds or (cards_total > 0 and cards_used >= cards_total)
|
||||
if exhausted:
|
||||
# 타결선은 목표가가 아니라 타결 상한가(견적 생성 시 박제) — 목표가를 넘어도
|
||||
# 상한 이내면 타결한다.
|
||||
ceiling = settle_ceiling(ctx)
|
||||
target = ctx.get("target_price", 0)
|
||||
if not ctx.get("closing_played"):
|
||||
ctx["force_closing"] = True
|
||||
return "가격협상"
|
||||
return "협상완료" if (ceiling > 0 and price <= ceiling) else c.get("next")
|
||||
return "협상완료" if (target > 0 and price <= target) else c.get("next")
|
||||
ok = False
|
||||
elif cond == "default":
|
||||
ok = True
|
||||
@@ -261,42 +197,32 @@ class ChatEngine:
|
||||
|
||||
def _pick_wildcard(self, session: ChatSession) -> str:
|
||||
"""앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
|
||||
앵커가 이하로 유도한다. 그 외 구간은 견적에서 선택한 와일드카드의 전술로 카운터하고,
|
||||
낼 카드가 없으면 일반 가격협상(카드 플레이)으로 돌린다.
|
||||
앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
|
||||
|
||||
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
|
||||
견적에서 실제 선택한 와일드카드(중간값 절충·목표가 선제안 등)와 매핑되지 않은 채
|
||||
'와일드카드를 하나라도 골랐으면' 조건만으로 발동해, 선택하지도 않은 재원부족 멘트가
|
||||
노출되는 오작동이 있었다.
|
||||
"""
|
||||
ctx = session.context
|
||||
price = ctx.get("input_price", 0)
|
||||
anchor = ctx.get("anchor_price", 0)
|
||||
target = ctx.get("target_price", 0)
|
||||
if anchor > 0 and price <= anchor * self.rules.wildcard_1pct_ratio:
|
||||
offer_1pct = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 — 10원 반올림(앵커·카운터와 통일)
|
||||
# 제안가 공통 유효조건(≤목표가 · <제시가 · 직전 당사 제안 이상=역행 금지)은 시스템 1% 카드에도
|
||||
# 동일하게 건다. 기본 앵커 밴드에선 수학적으로 항상 통과하지만 극단 데이터를 방어한다.
|
||||
prev_customer = ctx.get("prev_customer_price") or 0
|
||||
if 0 < offer_1pct < price and (target <= 0 or offer_1pct <= target) and offer_1pct >= prev_customer:
|
||||
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||
ctx["wildcard_used"] = True
|
||||
ctx["offer_1pct"] = offer_1pct
|
||||
record_offer(ctx, Offer(price=offer_1pct, variable="offer_1pct",
|
||||
prev_customer=int(prev_customer or anchor), prev_partner=int(price)))
|
||||
return "wild_card_1pct"
|
||||
# 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
|
||||
# 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
|
||||
ctx["wildcard_used"] = True
|
||||
ctx["offer_1pct"] = int(price * 0.99 / 10 + 0.5) * 10 # 1% 인하가 (멘트 변수) — 10원 반올림(앵커·카운터와 통일)
|
||||
ctx["pending_counter_price"] = ctx["offer_1pct"] # 수락 시 이 가격으로 타결
|
||||
return "wild_card_1pct"
|
||||
# 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
|
||||
# (구현 전에는 이 구간이 일반 가격협상으로 회귀해 선택형 WC 가 영영 발동하지 않던 갭.)
|
||||
if anchor > 0 and price <= anchor * self.rules.wildcard_entry_ratio:
|
||||
for number in (ctx.get("selected_wild_card_numbers") or []):
|
||||
number = str(number)
|
||||
spec = spec_from_context(ctx, number)
|
||||
# 종결 전용 카드(최종 통보·중간값 절충)는 여기서 안 꺼낸다 — 종결 국면의 마지막 한 방으로 예약.
|
||||
# 이미 쓴 카드도 제외(같은 멘트 반복 방지).
|
||||
if not available(spec, ctx) or is_played(ctx, number):
|
||||
continue
|
||||
offer = compute_offer_detail(spec, ctx)
|
||||
if offer is not None:
|
||||
counter = compute_counter(tactic_for(str(number)), ctx)
|
||||
if counter is not None:
|
||||
ctx["wildcard_used"] = True
|
||||
record_offer(ctx, offer)
|
||||
ctx["active_wild_card_number"] = number
|
||||
mark_played(ctx, number)
|
||||
ctx["pending_counter_price"] = counter
|
||||
ctx["active_wild_card_number"] = str(number)
|
||||
return "wild_card_dynamic"
|
||||
return "가격협상"
|
||||
|
||||
@@ -314,19 +240,6 @@ class ChatEngine:
|
||||
if "anchor_price" in ctx:
|
||||
# anchoring_price = DB 시드 기본 카드/sessions 컬럼 표기, anchor_price = 카드 에디터 표기.
|
||||
out["anchor"] = out["anchor_price"] = out["anchoring_price"] = int(ctx["anchor_price"])
|
||||
# 용어 토큰 — 회사 용어 사전(labels)이 있으면 그 단어, 없으면 카탈로그 기본값.
|
||||
# 조사가 붙는 자리를 위해 {label_supplier_를} 같은 파생 키도 함께 만든다.
|
||||
labels = ctx.get("labels") or {}
|
||||
for token, (label_key, fallback) in _SCRIPT_LABELS.items():
|
||||
word = labels.get(label_key) or fallback
|
||||
out[token] = word
|
||||
for form in ("는", "가", "를", "와"):
|
||||
out[f"{token}_{form}"] = _josa(word, form)
|
||||
# 기준가 호칭은 회사 용어가 아니라 공급사 관점 고정 — loader 박제값(없으면 '공급가').
|
||||
price_word = str(ctx.get("item_price_label") or _SUPPLIER_PRICE_LABEL)
|
||||
out["label_item_price"] = price_word
|
||||
for form in ("는", "가", "를", "와"):
|
||||
out[f"label_item_price_{form}"] = _josa(price_word, form)
|
||||
# 카드 에디터 카탈로그의 협력사명/상품명(partner_name·product_name) 치환.
|
||||
if ctx.get("partner_name"):
|
||||
out["partner_name"] = str(ctx["partner_name"])
|
||||
@@ -340,51 +253,43 @@ class ChatEngine:
|
||||
ilp = ctx.get("internet_lowest_price") or 0
|
||||
if ilp > 0:
|
||||
out["internet_lowest_price"] = out["internet_min_price"] = int(ilp)
|
||||
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.OFFER_VARIABLES 산식과 동일 정의.
|
||||
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.compute_counter 산식과 동일 정의.
|
||||
anchor = ctx.get("anchor_price") or 0
|
||||
target = ctx.get("target_price") or 0
|
||||
# 표시 기준값 — 제안이 확정된 턴이면 그 계산에 쓴 재료(pending_offer)를 쓴다.
|
||||
# prev_customer_price 는 확정 즉시 새 제안가로 갱신되므로, 그대로 읽으면 멘트가
|
||||
# "당사 제안과 귀사 제안의 절반이 당사 제안" 같은 자기모순이 된다.
|
||||
pending_offer = ctx.get("pending_offer") or {}
|
||||
prev_customer = int(pending_offer.get("prev_customer") or ctx.get("prev_customer_price") or anchor or 0)
|
||||
partner_price = int(pending_offer.get("prev_partner") or ctx.get("prev_partner_price") or ctx.get("input_price") or 0)
|
||||
offer_price = int(pending_offer.get("price") or ctx.get("pending_counter_price") or 0)
|
||||
offer_variable = pending_offer.get("variable") or ""
|
||||
if "input_price" in ctx:
|
||||
out["prev_partner_price"] = int(ctx.get("prev_partner_price") or ctx["input_price"])
|
||||
prev_customer = ctx.get("prev_customer_price") or anchor
|
||||
if prev_customer:
|
||||
out["prev_customer_price"] = prev_customer
|
||||
if partner_price:
|
||||
out["prev_partner_price"] = partner_price
|
||||
if offer_price:
|
||||
out["counter_price"] = offer_price
|
||||
# 파생 가격(절충가·중간가) — 제안가로 확정된 변수는 그 금액을 그대로 쓴다(멘트에 보이는 금액과
|
||||
# 수락 시 타결가는 항상 같아야 한다). 나머지는 참고 인용이므로 tactics 산식으로 채운다.
|
||||
# 산식을 여기 복사해 두면 갱신 시점 차이로 표시가와 제안가가 갈라지므로 정의를 호출만 한다.
|
||||
# 어느 변수가 제안가인지 모르는 진행 중 세션(구버전 기록)은 종전대로 전부 제안가로 고정한다.
|
||||
for name in _DERIVED_PRICE_VARIABLES:
|
||||
if offer_price and (name == offer_variable or not offer_variable):
|
||||
out[name] = offer_price
|
||||
continue
|
||||
value = OFFER_VARIABLES[name](target, anchor, partner_price, prev_customer)
|
||||
if value:
|
||||
out[name] = int(value / 10 + 0.5) * 10 # 10원 반올림 — compute_offer 와 동일
|
||||
# 인하율 = (협상 기준가 - 제시가) / 기준가 * 100. 기준가 없으면 미표시(0.0).
|
||||
# 제시가가 기준가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
|
||||
out["prev_customer_price"] = int(prev_customer)
|
||||
if anchor and target:
|
||||
out["target_mid_price"] = int(round((anchor + target) / 2))
|
||||
if prev_customer and "input_price" in ctx:
|
||||
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
|
||||
if ctx.get("pending_counter_price"):
|
||||
# 카운터 제시 중: 멘트에 보이는 제시가와 수락 시 타결가(pending)를 반드시 일치시킨다.
|
||||
# 절충/중간 변수(middle_price·target_mid_price)는 vars_for 재계산 값이 compute_counter 의
|
||||
# target 클램프·prev_customer 갱신과 어긋나, 멘트엔 1,740,000 이 보이는데 실제로는
|
||||
# 1,700,000 으로 타결되던 버그(표시가≠투찰가)가 있었다. pending 은 이 시점 유일한 '제안가'이므로
|
||||
# 세 변수 모두 pending 으로 고정한다(카운터 제시 턴에만 적용 — 비-카운터 렌더는 원 계산값 유지).
|
||||
pending_i = int(ctx["pending_counter_price"])
|
||||
out["counter_price"] = pending_i
|
||||
out["middle_price"] = pending_i
|
||||
out["target_mid_price"] = pending_i
|
||||
# 인하율 = (기존 공급가(상품단가) - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
|
||||
# 제시가가 기존가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
|
||||
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
|
||||
# 문구는 discount_phrase 로 별도 제공한다(가격협상_확인 멘트가 사용).
|
||||
# 기준가 호칭은 공급사 화면 고정 용어('공급가') — loader 가 박제한 값.
|
||||
base = ctx.get("item_price") or 0
|
||||
label = ctx.get("item_price_label") or _SUPPLIER_PRICE_LABEL
|
||||
if base > 1 and "input_price" in ctx:
|
||||
rate = ((base - ctx["input_price"]) / base) * 100
|
||||
out["discount_rate"] = f"{max(0.0, rate):.1f}"
|
||||
if rate >= 0.05:
|
||||
out["discount_phrase"] = f"기존 {label} 대비 약 **{rate:.1f}%** 인하된 금액입니다. "
|
||||
out["discount_phrase"] = f"기존 공급가 대비 약 **{rate:.1f}%** 인하된 금액입니다. "
|
||||
elif rate <= -0.05:
|
||||
out["discount_phrase"] = (
|
||||
f"기존 {label}(**{int(base)}원**)보다 약 **{abs(rate):.1f}%** 높은 금액입니다. ")
|
||||
f"기존 공급가(**{int(base)}원**)보다 약 **{abs(rate):.1f}%** 높은 금액입니다. ")
|
||||
else:
|
||||
out["discount_phrase"] = f"기존 {_josa(label, '와')} 동일한 수준의 금액입니다. "
|
||||
out["discount_phrase"] = "기존 공급가와 동일한 수준의 금액입니다. "
|
||||
else:
|
||||
out["discount_rate"] = "0.0"
|
||||
out["discount_phrase"] = ""
|
||||
@@ -401,14 +306,13 @@ class ChatEngine:
|
||||
def _render(self, session: ChatSession, step_key: Optional[str]) -> StepView:
|
||||
if not step_key or step_key not in self.scripts:
|
||||
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
|
||||
# 가드레일(최후 방어선): 구매자 대리는 타결 상한가를 넘겨 타결하지 않는다.
|
||||
# 상한 = 견적 생성 시 박제한 done_ceiling_price(목표가×(1+타결상한율)), 미박제면 목표가.
|
||||
# 목표가를 조금 넘어도 상한 이내면 타결이 정상이므로 여기서 뒤집지 않는다.
|
||||
# 상한까지 넘은 경우만 결렬로 강제 전환한다.
|
||||
# 가드레일(최후 방어선): 구매자 대리는 목표가 초과로 절대 타결하지 않는다.
|
||||
# 카운터 클램프·종결 규칙이 정상이면 도달하지 않지만, 스크립트 편집 실수 등으로
|
||||
# 성공 스텝에 초과가로 진입하면 결렬로 강제 전환한다. (재협상 흐름 한정)
|
||||
if step_key in _SUCCESS_STEPS and self.rq_type == "재협상":
|
||||
ctx = session.context
|
||||
ceiling = settle_ceiling(ctx)
|
||||
if ceiling > 0 and ctx.get("input_price", 0) > ceiling:
|
||||
target = ctx.get("target_price") or 0
|
||||
if target > 0 and ctx.get("input_price", 0) > target:
|
||||
step_key = "협상실패"
|
||||
node = self.scripts[step_key]
|
||||
session.step = step_key
|
||||
@@ -422,14 +326,11 @@ class ChatEngine:
|
||||
elif step_key in _FAILURE_STEPS:
|
||||
session.context["final_outcome"] = "failure"
|
||||
outcome = session.context.get("final_outcome") if chat_end else None
|
||||
# 선택지도 스크립트와 같은 변수 치환을 태운다 — 배송형태 보기가 회사 용어({label_delivery_type_1} 등)라
|
||||
# 치환을 건너뛰면 사용자에게 토큰 원문이 그대로 보인다.
|
||||
step_vars = self._vars(session)
|
||||
return StepView(
|
||||
step=step_key,
|
||||
script=self.repo.format_script(node.get("script", ""), step_vars),
|
||||
script=self.repo.format_script(node.get("script", ""), self._vars(session)),
|
||||
input_mode=node.get("next_input_mode", "null"),
|
||||
input_options=[self.repo.format_script(o, step_vars) for o in node.get("input_options", [])],
|
||||
input_options=node.get("input_options", []),
|
||||
chat_end=bool(node.get("chat_end")),
|
||||
client_step=self.step_map.get(step_key, step_key),
|
||||
needs_card_selection=(step_key == "가격협상"),
|
||||
@@ -438,13 +339,9 @@ class ChatEngine:
|
||||
)
|
||||
|
||||
def _error(self, session: ChatSession, msg: str) -> StepView:
|
||||
# 에러 재렌더도 정상 렌더와 같은 변수 치환을 태운다 — 여기만 raw 로 두면
|
||||
# 가격 오입력 시 옵션 버튼에 {label_*} 토큰이 그대로 노출된다.
|
||||
node = self.scripts.get(session.step, {})
|
||||
step_vars = self._vars(session)
|
||||
return StepView(
|
||||
step=session.step, script=self.repo.format_script(node.get("script", ""), step_vars),
|
||||
input_mode=node.get("next_input_mode", "null"),
|
||||
input_options=[self.repo.format_script(o, step_vars) for o in node.get("input_options", [])],
|
||||
step=session.step, script=node.get("script", ""),
|
||||
input_mode=node.get("next_input_mode", "null"), input_options=node.get("input_options", []),
|
||||
chat_end=session.ended, client_step=self.step_map.get(session.step, session.step), error=msg,
|
||||
)
|
||||
@@ -19,7 +19,6 @@ from typing import Optional
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from negotiation.cards.domain.tactics import build_card_spec
|
||||
from negotiation.chat.infra.repository.nego_context_crud import INegoContextCRUD, NegoContextCRUD
|
||||
from negotiation.qtable.domain.model.snapshot import PartnerType
|
||||
|
||||
@@ -39,10 +38,7 @@ class NegotiationDbContext:
|
||||
rq_type: str # 재협상(1:1) | 재견적(1:N) — sessions.qt_type 으로 판별
|
||||
target_price: int # 목표 매입가(원) — sessions.target_price
|
||||
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
|
||||
done_ceiling_price: int # 타결 상한가 — sessions.done_ceiling_price(생성 시 박제). 없으면 target
|
||||
item_price: int # 협상 기준가(고객사가 관리하는 가격 — 공급가 또는 매입가) — 인하율 멘트용. 없으면 0
|
||||
item_price_label: str # 협상 멘트에서 기준가를 부르는 말(회사 용어 설정 → 없으면 카탈로그 기본값)
|
||||
labels: dict # 회사 용어 사전(companies.settings.labels) — 스크립트 {label_*} 토큰 치환용
|
||||
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
||||
internet_lowest_price: int # 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용. 미수집이면 0
|
||||
partner_name: Optional[str] # 협력사명(suppliers.name) — 카드 {partner_name} 치환용. 없으면 None
|
||||
product_name: Optional[str] # 상품명(items.name) — 카드 {product_name} 치환용. 없으면 None
|
||||
@@ -52,9 +48,6 @@ class NegotiationDbContext:
|
||||
selected_nego_card_numbers: list[str] # 견적 생성 시 선택된 일반 협상카드 번호(card.nego_cards.number)
|
||||
selected_wild_card_numbers: list[str] # 견적 생성 시 선택된 와일드카드 번호(card.wild_cards.number)
|
||||
card_count: Optional[int] # 협상카드 사용 횟수 상한(quotation_settings.card_count). None=상한 미적용
|
||||
# 카드번호 → 전술 {offer_variable, min_round, closing}. 스크립트 파싱 + tactic JSONB 로 시작 시 1회 확정 —
|
||||
# 진행 중 협상은 카드 멘트가 도중에 바뀌어도 시작 시점 전술로 끝까지 간다(세션 컨텍스트에 박제).
|
||||
card_specs: dict
|
||||
|
||||
|
||||
class NegotiationContextLoader:
|
||||
@@ -74,10 +67,8 @@ class NegotiationContextLoader:
|
||||
err, row = await self.crud.get_session_row(s, sid)
|
||||
if err != ErrorType.SUCCESS or row is None:
|
||||
return None
|
||||
qt_type, target_price, anchoring_price, done_ceiling_price, item_id, quotation_id, supplier_id = row
|
||||
qt_type, target_price, anchoring_price, item_id, quotation_id, supplier_id = row
|
||||
target = int(target_price or 0)
|
||||
# 타결 상한가: 견적 생성 시 박제(목표가×(1+타결상한율)). 옛 세션은 NULL → 목표가로 폴백.
|
||||
ceiling = int(done_ceiling_price or 0) or target
|
||||
|
||||
# 앵커링가: 세션 생성 시 박제된 값(anchoring_price)을 그대로 사용 — 협상 중 불변.
|
||||
# 박제가 없으면(데이터 이상) 무할인 폴백 anchor=target + WARN — 앵커링 v1.2 정책상
|
||||
@@ -94,9 +85,8 @@ class NegotiationContextLoader:
|
||||
# 매핑이 없거나 미지정이면 None → 호출부 기본값.
|
||||
_, supplier_type = await self.crud.get_supply_type(s, supplier_id, item_id)
|
||||
|
||||
# 협상 기준가 + 그 호칭 — 어느 컬럼을 쓸지는 고객사 설정(hidden_fields)이 정한다(crud).
|
||||
# 없으면 0(인하율 멘트 미표시).
|
||||
_, (item_price, item_price_label, labels) = await self.crud.get_item_baseline(s, item_id)
|
||||
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
|
||||
_, item_price = await self.crud.get_item_price(s, item_id)
|
||||
|
||||
# 인터넷 최저가(LPS 수집 대표값) — 없으면 0(시장가 인용 카드는 값 있을 때만 치환).
|
||||
_, internet_lowest_price = await self.crud.get_item_lowest_price(s, item_id)
|
||||
@@ -116,19 +106,7 @@ class NegotiationContextLoader:
|
||||
# 견적 생성 모달에서 고른 카드셋. 값이 없으면 운영 DB 기준으로 "선택 카드 없음"이다.
|
||||
# 데모/직접호출 경로(DB context 없음)만 ChatService 에서 기존 기본 카드셋으로 폴백한다.
|
||||
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
|
||||
nego_rows, wild_rows = selected_cards
|
||||
selected_nego_cards = [number for number, _script, _tactic in nego_rows]
|
||||
selected_wild_cards = [number for number, _script, _tactic in wild_rows]
|
||||
# 카드 전술 확정 — "스크립트에 꽂힌 변수가 곧 전술"(제안가 파싱) + tactic JSONB(min_round·closing).
|
||||
card_specs = {}
|
||||
for number, script, tactic in [*nego_rows, *wild_rows]:
|
||||
spec = build_card_spec(script, tactic if isinstance(tactic, dict) else None)
|
||||
card_specs[number] = {
|
||||
"offer_variable": spec.offer_variable,
|
||||
"min_round": spec.min_round,
|
||||
"closing": spec.closing,
|
||||
"requires": list(spec.requires), # 세션-의존 변수 결측 시 미발동(available)
|
||||
}
|
||||
selected_nego_cards, selected_wild_cards = selected_cards
|
||||
|
||||
# 협상카드 사용 횟수 상한(견적 설정). 없으면 None → 상한 미적용(선택 카드 수로만 캡).
|
||||
_, card_count = await self.crud.get_card_count(s, sid)
|
||||
@@ -137,10 +115,7 @@ class NegotiationContextLoader:
|
||||
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
|
||||
target_price=target,
|
||||
anchor_price=anchor,
|
||||
done_ceiling_price=ceiling,
|
||||
item_price=item_price,
|
||||
item_price_label=item_price_label,
|
||||
labels=labels,
|
||||
internet_lowest_price=internet_lowest_price,
|
||||
partner_name=partner_name,
|
||||
product_name=product_name,
|
||||
@@ -150,7 +125,6 @@ class NegotiationContextLoader:
|
||||
selected_nego_card_numbers=selected_nego_cards,
|
||||
selected_wild_card_numbers=selected_wild_cards,
|
||||
card_count=card_count,
|
||||
card_specs=card_specs,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -121,7 +121,7 @@ class ScriptNaturalizer:
|
||||
def build_situation(context: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""세션 컨텍스트 → 정성 상황 라벨 (수치 미노출 — 숫자 환각 차단의 핵심).
|
||||
|
||||
가격구간: 제시가 vs 앵커/목표 관계, 라운드: 협상 진행 단계, 인하 진행: 협상 기준가 대비.
|
||||
가격구간: 제시가 vs 앵커/목표 관계, 라운드: 협상 진행 단계, 인하 진행: 기존 공급가 대비.
|
||||
"""
|
||||
out: Dict[str, Any] = {}
|
||||
rnd = context.get("round") or 0
|
||||
|
||||
@@ -13,9 +13,7 @@ from common.enums import DBType, ErrorType
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.logger import LOG
|
||||
from config.server_configs import agent_config
|
||||
from negotiation.cards.domain.tactics import (
|
||||
Offer, available, compute_offer_detail, is_played, mark_played, playable, record_offer, spec_from_context,
|
||||
)
|
||||
from negotiation.cards.domain.tactics import compute_counter, tactic_available, tactic_for
|
||||
from negotiation.chat.service.chat_engine import (
|
||||
_CHOICE_MODES, _PRICE_MODES, ChatEngine, ChatSession, StepView,
|
||||
)
|
||||
@@ -43,8 +41,6 @@ _DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_reven
|
||||
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
|
||||
_DEFAULT_PARTNER_NAME = "귀사" # 협력사명 — suppliers.name 미기재/데모 시 폴백(카드 {partner_name})
|
||||
_DEFAULT_PRODUCT_NAME = "본 상품" # 상품명 — items.name 미기재/데모 시 폴백(카드 {product_name})
|
||||
_DEFAULT_ITEM_PRICE_LABEL = "공급가" # 협상 기준가 호칭(공급사 화면 고정 용어) — DB 컨텍스트 없는 데모/직접호출 경로 폴백
|
||||
# (negodata 용어 카탈로그 item.price 의 base 와 같아야 표기가 갈리지 않는다)
|
||||
|
||||
|
||||
class ChatService:
|
||||
@@ -112,19 +108,12 @@ class ChatService:
|
||||
# 목표가/앵커링가: sessions 행(생성 시 박제된 anchoring_price) → 박제 ‰ → 1% 폴백 (loader).
|
||||
"anchor_price": db_ctx.anchor_price if db_ctx else _DEFAULT_ANCHOR_PRICE,
|
||||
"target_price": db_ctx.target_price if db_ctx else _DEFAULT_TARGET_PRICE,
|
||||
# 타결 상한가(sessions.done_ceiling_price 박제) — 타결 판정선이자 카드 제안가 상한.
|
||||
# 목표가를 조금 넘어도 이 이하면 타결한다. 미박제/데모는 목표가와 같다.
|
||||
"done_ceiling_price": db_ctx.done_ceiling_price if db_ctx else _DEFAULT_TARGET_PRICE,
|
||||
# 협력사명/상품명 — 카드 스크립트 {partner_name}·{product_name} 치환용(loader). 없으면 폴백.
|
||||
"partner_name": (db_ctx.partner_name if db_ctx and db_ctx.partner_name else _DEFAULT_PARTNER_NAME),
|
||||
"product_name": (db_ctx.product_name if db_ctx and db_ctx.product_name else _DEFAULT_PRODUCT_NAME),
|
||||
"round": 0,
|
||||
# 협상 기준가(고객사가 관리하는 가격 — 공급가 또는 매입가) — 가격협상_확인 인하율 산출용.
|
||||
# 호칭은 회사 설정 라벨을 따른다("기존 {label} 대비 …" 멘트).
|
||||
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
||||
"item_price": db_ctx.item_price if db_ctx else 0,
|
||||
"item_price_label": db_ctx.item_price_label if db_ctx else _DEFAULT_ITEM_PRICE_LABEL,
|
||||
# 회사 용어 사전 — 스크립트의 {label_*} 토큰(협력사·목표가·배송형태 등) 치환용.
|
||||
"labels": (db_ctx.labels if db_ctx else {}),
|
||||
# 인터넷 최저가(items.internet_lowest_price, LPS 대표값) — 카드 {internet_lowest_price} 치환용.
|
||||
# 미수집(0)이면 vars_for 가 키를 만들지 않아 원형 유지(허위 시장가 표기 방지).
|
||||
"internet_lowest_price": db_ctx.internet_lowest_price if db_ctx else 0,
|
||||
@@ -134,9 +123,6 @@ class ChatService:
|
||||
"db_context_loaded": db_ctx is not None,
|
||||
"selected_nego_card_numbers": selected_nego_cards,
|
||||
"selected_wild_card_numbers": selected_wild_cards,
|
||||
# 카드번호 → 전술 {offer_variable, min_round, closing}. 시작 시 1회 박제(loader) —
|
||||
# 이후 카드 멘트가 바뀌어도 이 협상은 시작 시점 전술로 끝까지 간다.
|
||||
"card_specs": (db_ctx.card_specs if db_ctx else {}),
|
||||
"allow_selected_wildcards": True if db_ctx is None else bool(selected_wild_cards),
|
||||
},
|
||||
)
|
||||
@@ -304,17 +290,14 @@ class ChatService:
|
||||
decision = policy.select(ctx)
|
||||
session.used_action_ids.add(decision.action_id)
|
||||
card_id = self._card_id_for_action(engine, session, decision.action_id)
|
||||
# 카드번호 공용 이력 — 와일드/종결 경로와 같은 목록을 본다("한 협상 한 카드 1회" 단일 판정).
|
||||
mark_played(session.context, card_id)
|
||||
# 전술 실행: 카드가 제시할 금액(스크립트 파싱 결과)을 계산해 세션에 적재한다.
|
||||
# 전술 실행(재설계): 카드의 가격 행동 — 카운터 제시가를 계산해 세션에 적재한다.
|
||||
# pending 이 있으면 이 턴은 수락/거절 스텝(가격협상_카운터)으로 전환되고,
|
||||
# 협력사가 수락하면 이 가격으로 즉시 타결된다(chat_engine 의 수락 메커니즘).
|
||||
# 유효조건(≤목표가 · <제시가) 미달이면 None → 금액 없이 설득 멘트만 나간다(HOLD 강등).
|
||||
spec = spec_from_context(session.context, card_id)
|
||||
offer = compute_offer_detail(spec, session.context) if available(spec, session.context) else None
|
||||
counter = offer.price if offer else None
|
||||
if offer is not None:
|
||||
record_offer(session.context, offer)
|
||||
spec = tactic_for(card_id)
|
||||
counter = compute_counter(spec, session.context) if tactic_available(spec, session.context) else None
|
||||
if counter is not None:
|
||||
session.context["pending_counter_price"] = counter
|
||||
session.context["prev_customer_price"] = counter # 갑의 최신 포지션(middle_price 기준)
|
||||
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
|
||||
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
|
||||
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
|
||||
@@ -369,31 +352,20 @@ class ChatService:
|
||||
규칙층의 강제 결정이므로 RL 선택/학습을 우회한다."""
|
||||
ctx = session.context
|
||||
ctx["closing_played"] = True
|
||||
# 선택 와일드카드 중 종결 전용 카드(closing) — 이미 쓴 카드는 건너뛰고(같은 멘트 반복 방지),
|
||||
# 제안가 유효조건(≤목표가 · <제시가) 미달 카드도 건너뛴다(예: 절충가가 목표가 초과 → 미발동).
|
||||
closing_number, closing_offer = None, None
|
||||
for n in (ctx.get("selected_wild_card_numbers") or []):
|
||||
n = str(n)
|
||||
spec = spec_from_context(ctx, n)
|
||||
if not available(spec, ctx, closing_phase=True) or is_played(ctx, n):
|
||||
continue
|
||||
offer = compute_offer_detail(spec, ctx)
|
||||
if offer is not None:
|
||||
closing_number, closing_offer = n, offer
|
||||
break
|
||||
if closing_offer is None:
|
||||
# 선택 와일드카드 중 종결 전술 (WC-05/WC-03) — 순서대로 첫 매치.
|
||||
closing_number = next(
|
||||
(str(n) for n in (ctx.get("selected_wild_card_numbers") or []) if tactic_for(str(n)).closing),
|
||||
None,
|
||||
)
|
||||
counter = compute_counter(tactic_for(closing_number), ctx) if closing_number else None
|
||||
if counter is None:
|
||||
# 폴백 최후통첩: 목표가 제시 (여기 도달 = 제시가 > target 이므로 항상 유효한 카운터).
|
||||
closing_number = None
|
||||
target = int(ctx.get("target_price") or 0)
|
||||
price = int(ctx.get("input_price") or 0)
|
||||
if 0 < target < price:
|
||||
closing_offer = Offer(price=target, variable="target_price",
|
||||
prev_customer=int(ctx.get("prev_customer_price") or ctx.get("anchor_price") or 0),
|
||||
prev_partner=price)
|
||||
if closing_offer is None:
|
||||
counter = target if 0 < target < ctx.get("input_price", 0) else None
|
||||
if counter is None:
|
||||
return # 컨텍스트 이상 — 기존 가격협상 스텝 그대로(재제안 요구)
|
||||
mark_played(ctx, closing_number) # None(폴백 최후통첩)이면 no-op
|
||||
record_offer(ctx, closing_offer)
|
||||
ctx["pending_counter_price"] = counter
|
||||
ctx["prev_customer_price"] = counter
|
||||
|
||||
template = None
|
||||
if closing_number:
|
||||
@@ -469,12 +441,10 @@ class ChatService:
|
||||
|
||||
@staticmethod
|
||||
def _tactic_mask(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
|
||||
"""지금 플레이 가능한 action 만 True. HOLD(설득)는 발동조건만, 금액 카드는 제안가 유효까지
|
||||
본다(playable) — 무효 금액(역행·목표가 초과 등)이 멘트 글자로 나가는 것 자체를 막는다.
|
||||
"""전술 발동조건(min_round·가격구간)을 만족하는 action 만 True. HOLD(설득)는 항상 True.
|
||||
전부 True 면 None(마스크 불필요)."""
|
||||
ctx = session.context
|
||||
mask = np.array(
|
||||
[playable(spec_from_context(ctx, engine.mapper.get_card_id(a)), ctx)
|
||||
[tactic_available(tactic_for(engine.mapper.get_card_id(a)), session.context)
|
||||
for a in range(engine.action_space_size)],
|
||||
dtype=bool,
|
||||
)
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"_comment": "가격협상(카드선택) 턴에 출력할 협상 카드 스크립트. action_id(0~8) → 멘트. 선행 chat_server 의 nego_card_scripts 를 대체하는 중립 기본값(CLEANROOM.md). 실제 운영 시 card.nego_cards.script 로 override(내부 소스만 변경, 흐름 동일). 변수: {target}=목표가, {input_price}=직전 제시가, {anchor}=앵커가, {discount_rate}=기존가 대비 인하율(%).",
|
||||
"_comment": "가격협상(카드선택) 턴에 출력할 협상 카드 스크립트. action_id(0~8) → 멘트. 선행 chat_server 의 nego_card_scripts 를 대체하는 중립 기본값(CLEANROOM.md). 실제 운영 시 card.nego_cards.script 로 override(내부 소스만 변경, 흐름 동일). 변수: {target}=목표 매입가, {input_price}=직전 제시가, {anchor}=앵커가, {discount_rate}=기존가 대비 인하율(%).",
|
||||
"0": "제안해 주신 **{input_price}원**, 감사합니다. 다만 동일 품목의 시장 거래가를 감안하면 추가 조정 여력이 있어 보입니다. 한 번 더 검토해 가격을 제안해 주시겠어요?",
|
||||
"1": "적극적으로 협조해 주셔서 감사합니다. 현재 제시가는 {label_target_price}(**{target}원**)와는 아직 차이가 있습니다. 조금만 더 좁혀 주시면 우선협상 대상으로 검토하겠습니다.",
|
||||
"2": "좋은 제안 감사합니다. 다른 {label_supplier}들의 제안 수준을 고려할 때, 현재 금액으로는 경쟁력이 다소 부족합니다. 재검토된 가격을 부탁드립니다.",
|
||||
"1": "적극적으로 협조해 주셔서 감사합니다. 현재 제시가는 목표 매입가(**{target}원**)와는 아직 차이가 있습니다. 조금만 더 좁혀 주시면 우선협상 대상으로 검토하겠습니다.",
|
||||
"2": "좋은 제안 감사합니다. 다른 협력사들의 제안 수준을 고려할 때, 현재 금액으로는 경쟁력이 다소 부족합니다. 재검토된 가격을 부탁드립니다.",
|
||||
"3": "협상에 성실히 임해 주셔서 감사합니다. 내부 승인 기준에 맞추려면 앵커가({anchor}원) 수준에 가까운 제안이 필요합니다. 가능하신 범위에서 다시 제안해 주세요.",
|
||||
"4": "제시해 주신 조건은 의미 있는 진전입니다. 다만 거래를 확정하려면 조금 더 협조가 필요합니다. 한 차례 더 조정해 주시겠어요?",
|
||||
"4": "제시해 주신 인하율 약 {discount_rate}%는 의미 있는 진전입니다. 다만 거래를 확정하려면 조금 더 협조가 필요합니다. 한 차례 더 조정해 주시겠어요?",
|
||||
"5": "장기적인 협력 관계를 고려해 최대한 반영하고자 합니다. 현재 제시가에서 추가로 조정해 주시면 즉시 검토를 진행하겠습니다. 다시 제안 부탁드립니다.",
|
||||
"6": "검토 결과, 현재 제시가는 우리 기준을 충족하기 직전 단계입니다. 마지막으로 한 번 더 조정된 가격을 제안해 주시면 협상을 마무리할 수 있습니다.",
|
||||
"7": "성의 있는 제안 감사합니다. 다만 물량과 납기 조건을 함께 고려하면 {input_price}원은 다소 높습니다. {label_target_price}({target}원)에 가까운 금액을 제안해 주세요.",
|
||||
"7": "성의 있는 제안 감사합니다. 다만 물량과 납기 조건을 함께 고려하면 {input_price}원은 다소 높습니다. 목표 매입가({target}원)에 가까운 금액을 제안해 주세요.",
|
||||
"8": "긍정적으로 검토되고 있습니다. 내부 결재를 위해 명분이 조금 더 필요한 상황입니다. 가능하신 선에서 한 번 더 인하된 가격을 제안해 주시겠어요?"
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"서비스안내": {
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 {label_supplier} 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.",
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.",
|
||||
"editor_script_id": "서비스안내",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": [
|
||||
@@ -25,7 +25,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인": {
|
||||
"script": "본 안내는 {label_supplier} 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"editor_script_id": "담당자확인",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": [
|
||||
@@ -55,7 +55,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"정보변경_완료": {
|
||||
"script": "[정보변경]을 선택하셨습니다. {label_supplier} 관리 시스템에서 담당자 정보를 변경하신 뒤, 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내에 갱신되지 않으면 참여 의사가 없는 것으로 간주되어 해당 견적 건이 미참여로 처리될 수 있습니다.",
|
||||
"script": "[정보변경]을 선택하셨습니다. 협력사 관리 시스템에서 담당자 정보를 변경하신 뒤, 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내에 갱신되지 않으면 참여 의사가 없는 것으로 간주되어 해당 견적 건이 미참여로 처리될 수 있습니다.",
|
||||
"editor_script_id": "정보변경_완료",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"서비스안내": {
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 {label_supplier} 간 신규 물품 공급 협상을 위한 것으로, 귀사에 새로운 공급 기회를 제공하고자 합니다. 이용 방법 안내를 확인하신 뒤 [확인]을 눌러 주세요.",
|
||||
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 신규 물품 공급 협상을 위한 것으로, 귀사에 새로운 공급 기회를 제공하고자 합니다. 이용 방법 안내를 확인하신 뒤 [확인]을 눌러 주세요.",
|
||||
"editor_script_id": "서비스안내",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": ["확인"],
|
||||
@@ -19,7 +19,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"담당자확인": {
|
||||
"script": "본 안내는 {label_supplier} 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
|
||||
"editor_script_id": "담당자확인",
|
||||
"next_input_mode": "yes_no",
|
||||
"input_options": ["예", "아니오"],
|
||||
@@ -37,7 +37,7 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"정보변경_완료": {
|
||||
"script": "[정보변경]을 선택하셨습니다. {label_supplier} 관리 시스템에서 담당자 정보를 변경하신 뒤 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내 갱신되지 않으면 미참여로 처리될 수 있습니다.",
|
||||
"script": "[정보변경]을 선택하셨습니다. 협력사 관리 시스템에서 담당자 정보를 변경하신 뒤 고객센터로 새 견적 생성을 요청해 주세요. 24시간 이내 갱신되지 않으면 미참여로 처리될 수 있습니다.",
|
||||
"editor_script_id": "정보변경_완료",
|
||||
"next_input_mode": "null",
|
||||
"input_options": [],
|
||||
@@ -46,7 +46,7 @@
|
||||
"chat_end": true
|
||||
},
|
||||
"협상품목안내": {
|
||||
"script": "{company_name}는 아래 상품에 대해 신규 {label_supplier_를} 선정하고 있으며, 귀사를 초대하여 견적을 요청드립니다. 제출하신 견적은 복수 업체와의 비교 평가를 통해 {label_supplier} 선정에 반영됩니다. 상품 정보를 확인해 주세요.",
|
||||
"script": "{company_name}는 아래 상품에 대해 신규 공급사를 선정하고 있으며, 귀사를 초대하여 견적을 요청드립니다. 제출하신 견적은 복수 업체와의 비교 평가를 통해 공급사 선정에 반영됩니다. 상품 정보를 확인해 주세요.",
|
||||
"editor_script_id": "협상품목안내",
|
||||
"next_input_mode": "confirm",
|
||||
"input_options": ["네, 알겠습니다."],
|
||||
@@ -73,10 +73,10 @@
|
||||
"chat_end": false
|
||||
},
|
||||
"배송형태선택": {
|
||||
"script": "{label_delivery_type_를} 선택해 주세요.",
|
||||
"script": "배송 형태를 선택해 주세요.",
|
||||
"editor_script_id": "배송형태선택",
|
||||
"next_input_mode": "delivery_type",
|
||||
"input_options": ["{label_delivery_type_1}", "{label_delivery_type_2}", "{label_delivery_type_3}"],
|
||||
"input_options": ["협력사배송", "지정택배배송", "픽업배송"],
|
||||
"next_step": { "default": "가격협상_입력" },
|
||||
"type": "text",
|
||||
"chat_end": false
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"editor_script_id": "wild_card_1pct"
|
||||
},
|
||||
"wild_card_budget": {
|
||||
"script": "솔직히 말씀드리면 현재 내부 예산(재원) 사정상 제안을 그대로 수용하기 어렵습니다. 당사 {label_target_price}는 **{target}원**입니다. 이 가격에 맞춰 주신다면 즉시 계약을 진행하고자 합니다. 마지막으로 한 번 더 제안 부탁드립니다.",
|
||||
"script": "솔직히 말씀드리면 현재 내부 예산(재원) 사정상 제안을 그대로 수용하기 어렵습니다. 목표 매입가는 **{target}원**입니다. 이 가격에 맞춰 주신다면 즉시 계약을 진행하고자 합니다. 마지막으로 한 번 더 제안 부탁드립니다.",
|
||||
"type": "text",
|
||||
"chat_end": false,
|
||||
"next_input_mode": "price",
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
"""협상 퍼즈 하네스 — 랜덤 조건·랜덤 협력사 행동으로 N회 완주시키고 불변식 위반을 수집한다.
|
||||
시드 고정(재현 가능). test_ 접두사 없음 — pytest 수집 대상 아님, 수동 실행 전용:
|
||||
docker run --rm -v $PWD/agent:/work -w /work -e APP_ENV=local -e DB_HOST=host.docker.internal \
|
||||
o2o-negosium-agent sh -lc "pip install -q pytest pytest-asyncio httpx; python tests/fuzz_negotiation.py"
|
||||
|
||||
케이스마다 검사하는 불변식:
|
||||
1. 전 턴 success
|
||||
2. 같은 카드 2회 발동 금지
|
||||
3. 종결 전용(WC-03·05)은 가격협상_카운터에서만 / 비종결 와일드는 wild_card_dynamic 에서만
|
||||
4. 타결 시 타결가 ≤ 목표가
|
||||
5. 카운터/1% 수락으로 타결하면 그 멘트에 타결가 표기
|
||||
6. 멘트·버튼에 미치환 토큰({xxx}) 잔존 금지
|
||||
7. 턴 상한(60) 안에 반드시 종료
|
||||
"""
|
||||
import asyncio
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, "/work")
|
||||
|
||||
from router.v1.chat.protocol import Req_Chat # noqa: E402
|
||||
from services.chat_service import ChatService, reset_sessions # noqa: E402
|
||||
from tenancy.config_loader import TenantConfigLoader # noqa: E402
|
||||
from tenancy.registry import TenantEngineRegistry # noqa: E402
|
||||
from tests.test_card_tactics import _TENANTS_DIR, _cleanup, _seed_quote_session # noqa: E402
|
||||
|
||||
N = 100
|
||||
SEED = 20260805
|
||||
TARGET = 10_000
|
||||
NEGO_POOL = ["NGC-001", "NGC-002", "NGC-003", "NGC-004", "NGC-005",
|
||||
"NGC-007", "NGC-008", "NGC-010", "NGC-011"]
|
||||
WILD_POOL = ["WC-01", "WC-02", "WC-03", "WC-04", "WC-05"]
|
||||
CLOSING = {"WC-03", "WC-05"}
|
||||
TOKEN_RE = re.compile(r"(?<!\{)\{([a-z_0-9]+)\}(?!\})")
|
||||
|
||||
|
||||
class Supplier:
|
||||
"""랜덤 협력사 — 높은 시작가에서 점진 양보, 카운터는 확률적으로 수락/거절."""
|
||||
|
||||
def __init__(self, rng, anchor):
|
||||
self.rng = rng
|
||||
self.anchor = anchor
|
||||
self.price = TARGET * rng.uniform(1.02, 1.30)
|
||||
self.accept_p = rng.uniform(0.15, 0.5)
|
||||
|
||||
def next_price(self):
|
||||
p = int(self.price)
|
||||
# 다음 라운드를 위해 양보 — 가끔 앵커 밑까지 다이브(우선협상 유도).
|
||||
self.price *= self.rng.uniform(0.90, 0.99)
|
||||
if self.rng.random() < 0.15:
|
||||
self.price = self.anchor * self.rng.uniform(0.95, 1.04)
|
||||
return str(max(p, 100))
|
||||
|
||||
def choose(self, options):
|
||||
if "수락" in options:
|
||||
return "수락" if self.rng.random() < self.accept_p else "다른 가격 제시"
|
||||
if set(options) >= {"예", "아니오"}:
|
||||
return "예" if self.rng.random() < max(self.accept_p, 0.5) else "아니오"
|
||||
return options[0] if options else "확인"
|
||||
|
||||
|
||||
async def run_case(idx, rng):
|
||||
anchor = int(TARGET * rng.choice([0.99, 0.99, 0.97, 0.95, 1.0]))
|
||||
nego = rng.sample(NEGO_POOL, rng.randint(1, 5))
|
||||
wild = rng.sample(WILD_POOL, rng.randint(0, 5))
|
||||
sup = Supplier(rng, anchor)
|
||||
|
||||
reset_sessions()
|
||||
sid = uuid.uuid4()
|
||||
qid, ver = await _seed_quote_session(sid, nego, wild_numbers=wild, target=TARGET, anchor=anchor)
|
||||
violations, fired, settled, outcome, ended = [], [], None, None, False
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
ui, last_input = None, None
|
||||
for _turn in range(60):
|
||||
r = await svc.chat(eng, Req_Chat(session_id=str(sid), user_input=ui))
|
||||
if r.result.success is not True:
|
||||
violations.append(f"턴 실패 input={ui} msg={r.msg}")
|
||||
break
|
||||
script, opts = r.script or "", list(r.input_options or [])
|
||||
if TOKEN_RE.search(script):
|
||||
violations.append(f"미치환 토큰(script): {TOKEN_RE.findall(script)} @ {r.step}")
|
||||
for o in opts:
|
||||
if TOKEN_RE.search(o):
|
||||
violations.append(f"미치환 토큰(option): {o} @ {r.step}")
|
||||
if r.card_id:
|
||||
fired.append((r.step, r.card_id))
|
||||
if r.settled_price is not None:
|
||||
settled = r.settled_price
|
||||
# 카운터/1% '수락' 타결이면 마지막 카운터 멘트에 타결가가 보였어야 한다.
|
||||
if last_input in ("수락",) and str(settled) not in (last_counter or ""):
|
||||
violations.append(f"표시가≠타결가: {settled} not in counter script")
|
||||
if r.step in ("가격협상_카운터", "wild_card_dynamic", "wild_card_1pct"):
|
||||
last_counter = script
|
||||
if r.chat_end:
|
||||
outcome, ended = r.outcome, True
|
||||
break
|
||||
# 다음 입력 결정
|
||||
last_input = None
|
||||
if r.input_mode == "price":
|
||||
ui = sup.next_price()
|
||||
elif opts:
|
||||
ui = sup.choose(opts)
|
||||
last_input = ui
|
||||
else:
|
||||
ui = "확인"
|
||||
if not ended:
|
||||
violations.append("60턴 내 미종료")
|
||||
|
||||
# 카드 불변식
|
||||
ids = [c for _, c in fired]
|
||||
if len(ids) != len(set(ids)):
|
||||
violations.append(f"카드 중복: {ids}")
|
||||
for step, c in fired:
|
||||
if c in CLOSING and step != "가격협상_카운터":
|
||||
violations.append(f"종결 카드 {c} 가 {step} 에서 발동")
|
||||
if c.startswith("WC") and c not in CLOSING and step != "wild_card_dynamic":
|
||||
violations.append(f"비종결 와일드 {c} 가 {step} 에서 발동")
|
||||
if outcome == "success":
|
||||
if settled is None:
|
||||
violations.append("성공인데 settled 없음")
|
||||
elif settled > TARGET:
|
||||
violations.append(f"목표가 초과 타결: {settled}")
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver)
|
||||
return {"idx": idx, "anchor": anchor, "nego": nego, "wild": wild,
|
||||
"fired": fired, "settled": settled, "outcome": outcome, "violations": violations}
|
||||
|
||||
|
||||
async def main():
|
||||
rng = random.Random(SEED)
|
||||
results, bad = [], []
|
||||
for i in range(N):
|
||||
res = await run_case(i, random.Random(rng.random()))
|
||||
results.append(res)
|
||||
if res["violations"]:
|
||||
bad.append(res)
|
||||
tag = "OK " if not res["violations"] else "BAD"
|
||||
print(f"[{tag}] #{i:02d} anchor={res['anchor']} nego={len(res['nego'])} wild={len(res['wild'])} "
|
||||
f"fired={'→'.join(c for _, c in res['fired']) or '-'} settled={res['settled']} {res['outcome']}")
|
||||
ok = sum(1 for r in results if not r["violations"])
|
||||
succ = sum(1 for r in results if r["outcome"] == "success")
|
||||
print(f"\n===== {ok}/{N} clean · 타결 {succ} / 결렬 {N - succ} =====")
|
||||
for r in bad:
|
||||
print(f"\n#{r['idx']} 위반: nego={r['nego']} wild={r['wild']} anchor={r['anchor']}")
|
||||
for v in r["violations"]:
|
||||
print(" -", v)
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
await DB_SESSION_MNG.dispose_all()
|
||||
sys.exit(0 if not bad else 1)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -53,7 +53,7 @@ async def test_4_4_company_id_auto_onboard():
|
||||
eng = await _reg().get_engine(COMPANY_ID)
|
||||
assert eng.tenant_id == COMPANY_ID
|
||||
assert eng.company_id == COMPANY_ID # 학습/세션이 이 company_id 로 격리
|
||||
assert eng.action_space_size == 9 # DB 카탈로그 9장(NGC-006·009 소프트삭제)
|
||||
assert eng.action_space_size == 11 # base 기본 카드(162×11 정합)
|
||||
assert eng.state_space_size == 162
|
||||
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ async def test_selected_cards_only_are_played(db_engine):
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4())) # 자동 온보딩(_base type:db → 실 DB 카탈로그)
|
||||
assert eng.action_space_size == 9 # 카탈로그 9장(NGC-006·009 소프트삭제)
|
||||
assert eng.action_space_size == 11 # 카탈로그 11장(NGC-001~011)
|
||||
|
||||
svc = ChatService()
|
||||
played = []
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"""카드 전술 검증 — "스크립트에 꽂힌 변수가 곧 전술" (파싱 + 변수별 유효조건 + tactic JSONB).
|
||||
"""카드 전술 재설계 검증 — "멘트 카드 → 전술 카드" (가격 행동 실행 계층).
|
||||
|
||||
① 제안가 파싱(마지막 제안가 변수) + 변수별 계산식 결정론
|
||||
② 변수 공통 유효조건 — 목표가 초과·제시가 이상이면 미발동(클램프 아님 — IMK 8AB0 회귀)
|
||||
③ 카운터 수락 = 즉시 타결 / 거절 = 재입력 + pending 폐기
|
||||
④ 목표가 초과 타결 금지 가드(성공 스텝 진입 차단)
|
||||
⑤ 와일드 진입 — 종결 전용 카드 예약(중반 미발동) + 카드 이력 공유(중복 발동 차단, IMK BB9A 회귀)
|
||||
⑥ E2E: 견적 선택 카드(NGC-010 목표가 제안)의 카운터를 수락하면 settled=target
|
||||
⑦ E2E: 협력사가 target 초과를 고수하면 종결 전술(최후통첩) 후 결렬 — 고객사 이득 가드레일
|
||||
① 카운터 산식 결정론 + min(counter, target) 클램프 + 무의미 카운터(HOLD 강등)
|
||||
② 카운터 수락 = 즉시 타결 / 거절 = 재입력 + pending 폐기
|
||||
③ 목표가 초과 타결 금지 가드(성공 스텝 진입 차단)
|
||||
④ 선택형 와일드카드(WC-05 중간값 절충) 발동 — 1.02~1.05 구간 갭 해소
|
||||
⑤ E2E: 견적 선택 카드(NGC-009 조건부 가격 조정)의 카운터를 수락하면 settled=target
|
||||
⑥ E2E: 협력사가 target 초과를 고수하면 종결 전술(최후통첩) 후 결렬 — 고객사 이득 가드레일
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -16,8 +15,7 @@ from datetime import datetime, timedelta, timezone
|
||||
import pytest
|
||||
|
||||
from negotiation.cards.domain.tactics import (
|
||||
CardSpec, HOLD, available, build_card_spec, compute_offer,
|
||||
is_played, mark_played, parse_offer_variable, playable, spec_from_context,
|
||||
PriceAction, TacticSpec, compute_counter, tactic_available, tactic_for,
|
||||
)
|
||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
@@ -25,12 +23,6 @@ from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
|
||||
# 엔진 단위 테스트용 카드 스펙(로더가 DB 스크립트 파싱으로 만드는 것과 같은 형태).
|
||||
_SPECS = {
|
||||
"WC-02": {"offer_variable": "target_mid_price", "min_round": 1, "closing": False},
|
||||
"WC-05": {"offer_variable": "middle_price", "min_round": 1, "closing": True},
|
||||
}
|
||||
|
||||
|
||||
def _engine() -> ChatEngine:
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
|
||||
@@ -39,134 +31,47 @@ def _engine() -> ChatEngine:
|
||||
|
||||
def _session(step="가격협상_확인", **ctx_over):
|
||||
ctx = {"input_price": 10300, "anchor_price": 10000, "target_price": 10100,
|
||||
"round": 1, "allow_selected_wildcards": False, "card_specs": dict(_SPECS)}
|
||||
"round": 1, "allow_selected_wildcards": False}
|
||||
ctx.update(ctx_over)
|
||||
return ChatSession(session_id="00000000-0000-0000-0000-00000000e001", tenant_id="imarketkorea",
|
||||
company_id="imarketkorea", step=step, action_space_size=0, context=ctx)
|
||||
|
||||
|
||||
# ---- ① 제안가 파싱 + 계산식 ---------------------------------------------------
|
||||
def test_parse_offer_variable_last_offer_wins():
|
||||
"""제안가 변수가 여럿이면 마지막 것 — 카드 문장은 배경을 먼저, 제안을 마지막에 한다(WC-04)."""
|
||||
assert parse_offer_variable("적정가는 {anchoring_price}원이었으나 {target_price}원으로 제안") == "target_price"
|
||||
assert parse_offer_variable("{target_price}원을 제안 드립니다") == "target_price"
|
||||
# 읽어주기 변수만 있으면 설득 카드 — 제안가 없음
|
||||
assert parse_offer_variable("시장가 {internet_lowest_price}원 안팎, 제시가 {prev_partner_price}원") is None
|
||||
assert parse_offer_variable("가격 변수 없는 설득 멘트") is None
|
||||
assert parse_offer_variable(None) is None
|
||||
# WC-05 정본: 읽어주기(직전 제안·제시가) 뒤 절충가 제안
|
||||
assert parse_offer_variable("당사 제안 {prev_customer_price}원과 귀사 제안 {prev_partner_price}원을 절반씩, {middle_price}원으로") == "middle_price"
|
||||
# negodata 에디터 칩 표기(anchor_price)도 앵커가 제안으로 인식 — DB 시드 표기(anchoring_price)의 별칭
|
||||
assert parse_offer_variable("예산 한도는 {anchor_price}원입니다") == "anchor_price"
|
||||
|
||||
|
||||
def test_build_card_spec_merges_script_and_tactic():
|
||||
spec = build_card_spec("{target_price}원으로 제안", {"min_round": 2, "closing": True})
|
||||
assert spec == CardSpec(offer_variable="target_price", min_round=2, closing=True)
|
||||
# tactic 없음 → 기본값. offer_variable override 는 파싱보다 우선.
|
||||
assert build_card_spec("설득 멘트", None) == HOLD
|
||||
assert build_card_spec("멘트", {"offer_variable": "anchoring_price"}).offer_variable == "anchoring_price"
|
||||
|
||||
|
||||
def test_offer_formulas():
|
||||
# ---- ① 카운터 산식 (결정론 + 가드레일 클램프) --------------------------------
|
||||
def test_counter_formulas_and_clamp():
|
||||
ctx = {"input_price": 11000, "anchor_price": 9900, "target_price": 10000}
|
||||
offer = lambda var, c=None: compute_offer(CardSpec(offer_variable=var), c or ctx) # noqa: E731
|
||||
assert offer("target_price") == 10000
|
||||
assert offer("anchoring_price") == 9900
|
||||
assert offer("target_mid_price") == 9950 # (anchor+target)/2
|
||||
# 절충가: 갑 직전 포지션 폴백 = anchor → (8900+9500)/2 = 9200
|
||||
assert offer("middle_price", dict(ctx, input_price=9500, anchor_price=8900)) == 9200
|
||||
# 갑 직전 포지션이 있으면 그 기준: (9000+9500)/2 = 9250
|
||||
assert offer("middle_price", dict(ctx, input_price=9500, prev_customer_price=9000)) == 9250
|
||||
assert compute_counter(tactic_for("NGC-009"), ctx) == 10000 # COUNTER_TARGET
|
||||
assert compute_counter(tactic_for("NGC-007"), ctx) == 9900 # COUNTER_ANCHOR
|
||||
assert compute_counter(tactic_for("WC-02"), ctx) == 9950 # (anchor+target)/2
|
||||
# COUNTER_MID: 갑 직전 포지션 폴백 = anchor → (9900+11000)/2 = 10450 → target 클램프
|
||||
assert compute_counter(tactic_for("WC-05"), ctx) == 10000
|
||||
# 갑 직전 포지션이 있으면 그 기준: (9800+11000)/2 = 10400 → 역시 클램프 10000
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, prev_customer_price=9800)) == 10000
|
||||
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target → 10원 단위 반올림 9980
|
||||
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9980
|
||||
|
||||
|
||||
# ---- ② 변수 공통 유효조건 — 미발동(클램프 아님) --------------------------------
|
||||
def test_offer_over_target_does_not_fire_imk_8ab0():
|
||||
"""IMK 8AB0 회귀: 목표가 9,000 / 제시가 9,500 → 절충가 (8,910+9,500)/2 = 9,205 > 목표가.
|
||||
구현이 목표가로 깎아 부르면 '중간에서 만나자며 목표가를 부르는' 모순 — 클램프가 아니라 미발동이 정답."""
|
||||
ctx = {"input_price": 9500, "anchor_price": 8910, "target_price": 9000}
|
||||
assert compute_offer(CardSpec(offer_variable="middle_price"), ctx) is None
|
||||
|
||||
|
||||
def test_offer_at_or_above_input_price_does_not_fire():
|
||||
"""협력사 제시가가 이미 제안가 이하면 부를 이유가 없다 → 미발동."""
|
||||
def test_counter_meaningless_degrades_to_hold():
|
||||
"""협력사 제시가가 이미 카운터 이하면 카운터가 무의미 → None(순수 설득 유지)."""
|
||||
ctx = {"input_price": 9950, "anchor_price": 9900, "target_price": 10000}
|
||||
assert compute_offer(CardSpec(offer_variable="target_price"), ctx) is None # target ≥ 제시가
|
||||
assert compute_offer(CardSpec(offer_variable="anchoring_price"), dict(ctx, input_price=9900)) is None
|
||||
assert compute_counter(tactic_for("NGC-009"), ctx) is None # target(10000) ≥ 제시가
|
||||
assert compute_counter(TacticSpec(PriceAction.COUNTER_ANCHOR), dict(ctx, input_price=9900)) is None
|
||||
|
||||
|
||||
def test_offer_without_materials_does_not_fire():
|
||||
"""재료 결측(목표가·제시가·앵커) — 어떤 변수도 미발동."""
|
||||
assert compute_offer(CardSpec(offer_variable="target_price"), {"input_price": 11000}) is None # 목표가 없음
|
||||
assert compute_offer(CardSpec(offer_variable="anchoring_price"),
|
||||
{"input_price": 11000, "target_price": 10000}) is None # 앵커 없음
|
||||
assert compute_offer(HOLD, {"input_price": 11000, "target_price": 10000}) is None # 설득 카드
|
||||
assert compute_offer(CardSpec(offer_variable="없는변수"), {"input_price": 11000, "target_price": 10000}) is None
|
||||
def test_unknown_card_falls_back_to_hold():
|
||||
"""미등록 카드번호(데모 NGC-B*, 커스텀 COMP-*)는 HOLD — 기존 동작 그대로."""
|
||||
spec = tactic_for("NGC-B003")
|
||||
assert spec.price_action is PriceAction.HOLD
|
||||
assert compute_counter(spec, {"input_price": 11000, "target_price": 10000}) is None
|
||||
assert tactic_available(spec, {}) is True
|
||||
|
||||
|
||||
def test_available_min_round_and_closing_phase():
|
||||
spec2 = CardSpec(offer_variable="target_price", min_round=2)
|
||||
assert available(spec2, {"round": 1}) is False # min_round 미만
|
||||
assert available(spec2, {"round": 2}) is True
|
||||
closing = CardSpec(offer_variable="middle_price", closing=True)
|
||||
assert available(closing, {"round": 1}) is False # 종결 전용 — 중반 미발동(예약)
|
||||
assert available(closing, {"round": 1}, closing_phase=True) is True
|
||||
assert available(spec2, {"round": 3}, closing_phase=True) is False # 종결 국면엔 종결 카드만
|
||||
def test_tactic_availability_conditions():
|
||||
assert tactic_available(tactic_for("WC-04"), {"round": 1}) is False # min_round=2
|
||||
assert tactic_available(tactic_for("WC-04"), {"round": 2}) is True
|
||||
|
||||
|
||||
def test_tactic_offer_variable_overrides_parse():
|
||||
"""검증: tactic.offer_variable 명시 지정(negodata 셀렉트) — 파싱(마지막 변수) 대신 지정 변수 사용.
|
||||
기대결과: 멘트 마지막이 target_price 여도 지정한 anchoring_price 가 제안가 변수가 된다."""
|
||||
script = "적정가는 {anchoring_price}원이었으나 {target_price}원으로 제안 드립니다."
|
||||
assert build_card_spec(script).offer_variable == "target_price" # 자동: 마지막 변수
|
||||
spec = build_card_spec(script, {"offer_variable": "anchoring_price"})
|
||||
assert spec.offer_variable == "anchoring_price" # 명시 지정이 우선
|
||||
|
||||
|
||||
def test_available_requires_context_value():
|
||||
"""검증: 시장가 인용 카드(NGC-008류)의 requires 게이트 — build_card_spec 이 스크립트에서 잡아내고,
|
||||
기대결과: 컨텍스트에 인터넷 최저가가 없으면(0/결측) 미발동, 있으면 발동(퍼즈 #3·13·23·40 회귀)."""
|
||||
spec = build_card_spec("유사 거래는 {internet_lowest_price}원 안팎에서 합의되고 있습니다.")
|
||||
assert spec.requires == ("internet_lowest_price",)
|
||||
assert available(spec, {"round": 1}) is False # 결측
|
||||
assert available(spec, {"round": 1, "internet_lowest_price": 0}) is False # 미수집(0)
|
||||
assert available(spec, {"round": 1, "internet_lowest_price": 6300}) is True
|
||||
# 일반 카드는 requires 없음 — 기존 동작 그대로.
|
||||
assert build_card_spec("귀사와의 협력을 소중히 생각합니다.").requires == ()
|
||||
|
||||
|
||||
def test_offer_monotonic_no_regression():
|
||||
"""검증: 역행 금지(IMK 논의 — 절충 16,980 후 예산 상한 16,810 제시) 재현.
|
||||
기대결과: 직전 당사 제안보다 낮은 제안가 카드는 미발동(설득 폴백으로도 안 나감).
|
||||
직전 제안이 없으면 앵커 제시 허용, 같은 금액 재제시 허용, 더 높은 제안은 정상."""
|
||||
anchor_card = CardSpec(offer_variable="anchoring_price")
|
||||
ctx = {"round": 2, "target_price": 17_300, "anchor_price": 16_810, "input_price": 17_500}
|
||||
assert compute_offer(anchor_card, ctx) == 16_810 # 첫 카운터 전(포지션=앵커): 같은 금액 → 허용
|
||||
ctx["prev_customer_price"] = 16_980 # 절충 카드가 이미 16,980 을 부른 상태
|
||||
assert compute_offer(anchor_card, ctx) is None # 앵커 16,810 은 역행 → 미발동
|
||||
assert playable(anchor_card, ctx) is False # 멘트에 금액이 박히므로 설득 폴백도 금지
|
||||
assert compute_offer(CardSpec(offer_variable="target_price"), ctx) == 17_300 # 상향 제안은 정상
|
||||
|
||||
|
||||
def test_played_history_is_shared_by_number():
|
||||
ctx = {}
|
||||
assert is_played(ctx, "WC-05") is False
|
||||
mark_played(ctx, "WC-05")
|
||||
assert is_played(ctx, "WC-05") is True
|
||||
mark_played(ctx, "WC-05") # 재기록해도 1건 유지
|
||||
assert ctx["played_card_numbers"] == ["WC-05"]
|
||||
mark_played(ctx, None) # no-op(폴백 최후통첩)
|
||||
assert ctx["played_card_numbers"] == ["WC-05"]
|
||||
|
||||
|
||||
def test_spec_from_context_reads_snapshot_and_falls_back_to_hold():
|
||||
ctx = {"card_specs": dict(_SPECS)}
|
||||
assert spec_from_context(ctx, "WC-05") == CardSpec(offer_variable="middle_price", min_round=1, closing=True)
|
||||
assert spec_from_context(ctx, "NGC-B003") == HOLD # 미등록 카드(데모) 폴백
|
||||
assert spec_from_context({}, "WC-05") == HOLD # 스펙 미적재(구세션·데모) 폴백
|
||||
|
||||
|
||||
# ---- ③ 카운터 수락/거절 메커니즘 (엔진) ---------------------------------------
|
||||
# ---- ② 카운터 수락/거절 메커니즘 (엔진) ---------------------------------------
|
||||
def test_accept_counter_settles_at_counter_price():
|
||||
eng = _engine()
|
||||
s = _session(step="가격협상_카운터", pending_counter_price=10000)
|
||||
@@ -197,7 +102,7 @@ def test_wildcard_1pct_decline_keeps_original_price():
|
||||
assert s.context["input_price"] == 10000 # 거절 → 카운터 미적용
|
||||
|
||||
|
||||
# ---- ④ 목표가 초과 타결 금지 가드 --------------------------------------------
|
||||
# ---- ③ 목표가 초과 타결 금지 가드 --------------------------------------------
|
||||
def test_success_step_guard_rejects_over_target():
|
||||
eng = _engine()
|
||||
s = _session(input_price=10800, target_price=10000)
|
||||
@@ -205,46 +110,20 @@ def test_success_step_guard_rejects_over_target():
|
||||
assert view.step == "협상실패" # 초과가 성공 진입 → 결렬 강제
|
||||
|
||||
|
||||
# ---- ⑤ 와일드 진입 — 종결 예약 + 중복 차단 (IMK BB9A 회귀) ---------------------
|
||||
def test_selected_wildcard_fires_in_entry_zone_and_records_position():
|
||||
eng = _engine()
|
||||
# 10300: 1pct 존(≤10200) 밖, entry 존(≤10500) 안 + 비종결 WC-02 선택
|
||||
s = _session(input_price=10300, allow_selected_wildcards=True,
|
||||
selected_wild_card_numbers=["WC-02"])
|
||||
view = eng.advance(s, "예")
|
||||
assert view.step == "wild_card_dynamic"
|
||||
# 제안가 = (anchor 10000 + target 10100)/2 = 10050 ≤ target — 그대로 제시(클램프 없음)
|
||||
assert s.context["pending_counter_price"] == 10050
|
||||
assert s.context["prev_customer_price"] == 10050 # 갑 포지션 기록 — "당사 제안" 멘트 정합(BB9A ③)
|
||||
assert s.context["active_wild_card_number"] == "WC-02"
|
||||
assert is_played(s.context, "WC-02") # 카드 이력 기록
|
||||
# 수락 → 그 가격으로 타결
|
||||
view = eng.advance(s, "수락")
|
||||
assert view.step == "협상완료" and s.context["input_price"] == 10050
|
||||
|
||||
|
||||
def test_closing_card_is_reserved_never_fires_mid_negotiation():
|
||||
"""종결 전용 카드(WC-05)는 entry 존이라도 중반에 안 나간다 — 종결 국면의 마지막 한 방으로 예약.
|
||||
(BB9A 중복의 절반: 중반에 당겨 쓴 카드를 종결에서 또 쓰던 경로 차단.)"""
|
||||
# ---- ④ 선택형 와일드카드 발동 (1.02~1.05 구간 갭 해소) -------------------------
|
||||
def test_selected_wildcard_fires_in_entry_zone():
|
||||
eng = _engine()
|
||||
# 10300: 1pct 존(≤10200) 밖, entry 존(≤10500) 안 + WC-05 선택
|
||||
s = _session(input_price=10300, allow_selected_wildcards=True,
|
||||
selected_wild_card_numbers=["WC-05"])
|
||||
view = eng.advance(s, "예")
|
||||
assert view.step == "가격협상" # 종결 카드뿐 → 일반 카드 플레이로
|
||||
assert "active_wild_card_number" not in s.context
|
||||
assert not is_played(s.context, "WC-05") # 안 나갔으니 이력도 없음
|
||||
# 종결 국면에선 발동 가능 + 이력 없음 — 서비스 종결 루프가 이 카드를 쓴다
|
||||
spec = spec_from_context(s.context, "WC-05")
|
||||
assert available(spec, s.context, closing_phase=True) is True
|
||||
|
||||
|
||||
def test_played_wildcard_is_skipped_on_reentry():
|
||||
"""이미 쓴 카드는 같은 협상에서 다시 안 나간다 — 다음 후보로 넘어간다."""
|
||||
eng = _engine()
|
||||
s = _session(input_price=10300, allow_selected_wildcards=True, wildcard_used=False,
|
||||
selected_wild_card_numbers=["WC-02"], played_card_numbers=["WC-02"])
|
||||
view = eng.advance(s, "예")
|
||||
assert view.step == "가격협상" # 유일 후보가 사용됨 → 발동 없음
|
||||
assert view.step == "wild_card_dynamic"
|
||||
# 카운터 = (anchor 10000 + 10300)/2 = 10150 → target(10100) 클램프
|
||||
assert s.context["pending_counter_price"] == 10100
|
||||
assert s.context["active_wild_card_number"] == "WC-05"
|
||||
# 수락 → 그 가격으로 타결
|
||||
view = eng.advance(s, "수락")
|
||||
assert view.step == "협상완료" and s.context["input_price"] == 10100
|
||||
|
||||
|
||||
def test_unselected_wildcard_zone_still_falls_to_nego():
|
||||
@@ -307,7 +186,7 @@ def test_vars_for_supplies_tactic_variables():
|
||||
assert v1["target_mid_price"] == 10100
|
||||
|
||||
|
||||
# ---- ⑥⑦ E2E (실 DB — 견적 선택 카드 + 서비스 레이어) ---------------------------
|
||||
# ---- ⑤⑥ E2E (실 DB — 견적 선택 카드 + 서비스 레이어) ---------------------------
|
||||
from sqlalchemy import column, delete, insert, select, table # noqa: E402
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||
@@ -332,30 +211,24 @@ _T_QUOTATIONS = table(
|
||||
)
|
||||
_T_VNC = table("version_nego_cards", column("vnc_id"), column("version_id"), column("nego_card_id"), schema="card")
|
||||
_T_NEGO = table("nego_cards", column("nego_card_id"), column("number"), column("deleted"), schema="card")
|
||||
_T_VWC = table("version_wild_cards", column("vwc_id"), column("version_id"), column("wild_card_id"), schema="card")
|
||||
_T_WILD = table("wild_cards", column("wild_card_id"), column("number"), column("deleted"), schema="card")
|
||||
|
||||
|
||||
async def _card_uuid(number: str, *, wild=False):
|
||||
tbl, pk = (_T_WILD, _T_WILD.c.wild_card_id) if wild else (_T_NEGO, _T_NEGO.c.nego_card_id)
|
||||
|
||||
async def _card_uuid(number: str):
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(
|
||||
s, select(pk).where(tbl.c.number == number, tbl.c.deleted == False).limit(1)) # noqa: E712
|
||||
s, select(_T_NEGO.c.nego_card_id).where(
|
||||
_T_NEGO.c.number == number, _T_NEGO.c.deleted == False).limit(1)) # noqa: E712
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
async def _seed_quote_session(sid, selected_numbers, wild_numbers=(), target=10000, anchor=9900):
|
||||
async def _seed_quote_session(sid, selected_numbers, target=10000, anchor=9900):
|
||||
qid, ver_id, iid, sup = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
|
||||
now = datetime.now(timezone.utc)
|
||||
card_ids, wild_ids = {}, {}
|
||||
card_ids = {}
|
||||
for n in selected_numbers:
|
||||
card_ids[n] = await _card_uuid(n)
|
||||
assert card_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
|
||||
for n in wild_numbers:
|
||||
wild_ids[n] = await _card_uuid(n, wild=True)
|
||||
assert wild_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
|
||||
|
||||
def _seed(s_):
|
||||
async def run(s):
|
||||
@@ -370,11 +243,6 @@ async def _seed_quote_session(sid, selected_numbers, wild_numbers=(), target=100
|
||||
vnc_id=_uuid.uuid4(), version_id=ver_id, nego_card_id=card_ids[n]))
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
for n in wild_numbers:
|
||||
e = await DB_SESSION_MNG.add(s, insert(_T_VWC).values(
|
||||
vwc_id=_uuid.uuid4(), version_id=ver_id, wild_card_id=wild_ids[n]))
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
return await DB_SESSION_MNG.add(s, insert(_T_SESSIONS).values(
|
||||
session_id=sid, quotation_id=qid, item_id=iid, supplier_id=sup,
|
||||
qt_number=f"QT-TACTIC-{str(sid)[:8]}", qt_round=1, qt_type=1,
|
||||
@@ -392,18 +260,17 @@ async def _cleanup(sid, qid, ver_id):
|
||||
[DBType.MAIN.value],
|
||||
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.session_id == sid)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_VNC).where(_T_VNC.c.version_id == ver_id)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_VWC).where(_T_VWC.c.version_id == ver_id)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid))],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_e2e_counter_accept_settles_at_target(db_engine):
|
||||
"""견적 선택 카드 NGC-010(향후 거래 연계 — 스크립트 {target_price} 파싱 → 목표가 제안)의
|
||||
카운터를 수락하면 합의가 = 목표가(10000) — '수락 즉시 타결' 기획 결정의 E2E 검증."""
|
||||
"""견적 선택 카드 NGC-009(조건부 가격 조정 → COUNTER_TARGET)의 카운터를 수락하면
|
||||
합의가 = 목표가(10000) — '수락 즉시 타결' 기획 결정의 E2E 검증."""
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-010"])
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-009"])
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
@@ -412,9 +279,9 @@ async def test_e2e_counter_accept_settles_at_target(db_engine):
|
||||
r = None
|
||||
for ui in [None, "확인", "예", "확인", "11000", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||
# 가격협상 카드 턴 → NGC-010 카운터(target) 제시 스텝
|
||||
# 가격협상 카드 턴 → NGC-009 카운터(target) 제시 스텝
|
||||
assert r.step == "가격협상_카운터", f"카운터 스텝 기대, 실제 {r.step}"
|
||||
assert r.card_id == "NGC-010"
|
||||
assert r.card_id == "NGC-009"
|
||||
assert r.input_options == ["수락", "다른 가격 제시"]
|
||||
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="수락"))
|
||||
@@ -430,7 +297,7 @@ async def test_e2e_over_target_ends_in_failure_after_closing(db_engine):
|
||||
그래도 거절 → 결렬(협상실패). 목표가 초과로는 절대 타결되지 않는다."""
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-003"]) # 설득 카드 1장 → 빠른 소진
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-003"]) # HOLD 카드 1장 → 빠른 소진
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
@@ -454,46 +321,3 @@ async def test_e2e_over_target_ends_in_failure_after_closing(db_engine):
|
||||
assert r.settled_price is None # 초과가 타결 없음
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver_id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_e2e_bb9a_no_duplicate_wildcard_and_real_middle(db_engine):
|
||||
"""IMK BB9A 재현 E2E — 와일드카드 2장(WC-02·WC-05) + 설득 카드 1장.
|
||||
|
||||
기대 흐름(수정 후):
|
||||
· 중반 와일드 진입 = 비종결 WC-02 (종결 전용 WC-05 는 예약 — 구현 전엔 WC-05 가 먼저 나갔다)
|
||||
· 종결 국면 = WC-05, 절충가 = (당사 직전 제안 + 협력사 제시가)/2 실계산 (구현 전엔 목표가로 클램프)
|
||||
· 같은 카드 2회 발동 없음 + 종결 발동도 card_id 기록
|
||||
"""
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, ["NGC-003"], wild_numbers=["WC-02", "WC-05"])
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
session_id = str(sid)
|
||||
r = None
|
||||
# 10300: 1pct 존(≤ 9900×1.02=10098) 밖, entry 존(≤ 10395) 안 → 선택형 와일드 발동 구간
|
||||
for ui in [None, "확인", "예", "확인", "10300", "예"]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
|
||||
assert r.step == "wild_card_dynamic"
|
||||
assert r.card_id == "WC-02" # 종결 전용 WC-05 가 아니라 비종결 카드
|
||||
# WC-02 제안가 = (anchor 9900 + target 10000)/2 = 9950
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="다른 가격 제시"))
|
||||
# 10010 재제시 → 설득 카드(NGC-003) 1장 소진
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="10010"))
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="예"))
|
||||
assert r.step == "가격협상" and r.card_id == "NGC-003"
|
||||
# 10005 재제시 → 카드 소진 → 종결 국면: WC-05 절충가 = (9950 + 10005)/2 = 9980 (≤ target)
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="10005"))
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="예"))
|
||||
assert r.step == "가격협상_카운터"
|
||||
assert r.card_id == "WC-05" # 종결 발동도 카드 기록(구현 전 null)
|
||||
assert "9980" in r.script # 실제 절충가 — 목표가(10000) 클램프 아님
|
||||
|
||||
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="수락"))
|
||||
assert r.step == "협상완료"
|
||||
assert r.settled_price == 9980 # 표시가 = 타결가
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver_id)
|
||||
@@ -186,14 +186,11 @@ async def test_loader_with_crud_double(db_engine):
|
||||
|
||||
class _FakeCRUD(INegoContextCRUD):
|
||||
async def get_session_row(self, cdb, session_id):
|
||||
# (qt_type, target, anchoring_price, done_ceiling_price, item_id, quotation_id, supplier_id)
|
||||
# — 재견적(2)·앵커 미박제·타결상한 52,500(목표가 +5%)
|
||||
return ErrorType.SUCCESS, (2, 50000, None, 52500, uuid.uuid4(), uuid.uuid4(), uuid.uuid4())
|
||||
# (qt_type, target, anchoring_price, item_id, quotation_id, supplier_id) — 재견적(2)·앵커 미박제
|
||||
return ErrorType.SUCCESS, (2, 50000, None, uuid.uuid4(), uuid.uuid4(), uuid.uuid4())
|
||||
|
||||
async def get_item_baseline(self, cdb, item_id):
|
||||
# 기준가를 매입가로 고른 회사 + 거래상대 호칭을 '공급업체'로 바꾼 용어 사전.
|
||||
# 호칭은 crud 가 어떤 회사든 '공급가'(공급사 화면 고정 용어)로 내려준다.
|
||||
return ErrorType.SUCCESS, (7000, "공급가", {"supplier": "공급업체"})
|
||||
async def get_item_price(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 7000
|
||||
|
||||
async def get_item_lowest_price(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 6300 # 인터넷 최저가(items.internet_lowest_price)
|
||||
@@ -220,22 +217,14 @@ async def test_loader_with_crud_double(db_engine):
|
||||
return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE
|
||||
|
||||
async def get_quotation_card_numbers(self, cdb, quotation_id):
|
||||
# 행 = (number, script, tactic) — 스크립트 파싱 + tactic JSONB 로 card_specs 를 만든다
|
||||
return ErrorType.SUCCESS, (
|
||||
[("NGC-003", "설득 멘트(가격 변수 없음)", None),
|
||||
("NGC-008", "시장가 {internet_lowest_price}원 인용(읽기 전용 변수)", None)],
|
||||
[("WC-02", "이에 당사는 {target_mid_price}원을 역으로 제안 드립니다.", None)],
|
||||
)
|
||||
return ErrorType.SUCCESS, (["NGC-003", "NGC-008"], ["WC-02"]) # 견적 선택 카드
|
||||
|
||||
ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4()))
|
||||
assert ctx is not None
|
||||
assert ctx.rq_type == "재견적" # qt_type=2(1:N)
|
||||
assert ctx.target_price == 50000
|
||||
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
|
||||
assert ctx.done_ceiling_price == 52500 # 타결 상한가 박제값(목표가 +5%)
|
||||
assert ctx.item_price == 7000
|
||||
assert ctx.item_price_label == "공급가" # 기준가 호칭이 멘트까지 전달되는지
|
||||
assert ctx.labels == {"supplier": "공급업체"} # 회사 용어 사전이 스크립트 토큰용으로 실리는지
|
||||
assert ctx.internet_lowest_price == 6300 # 인터넷 최저가 로드 확인
|
||||
assert ctx.card_count == 3 # 협상카드 사용 횟수 상한 로드 확인
|
||||
assert ctx.partner_name == "테스트협력사"
|
||||
@@ -245,14 +234,6 @@ async def test_loader_with_crud_double(db_engine):
|
||||
assert ctx.partner_type is PartnerType.NONE
|
||||
assert ctx.selected_nego_card_numbers == ["NGC-003", "NGC-008"]
|
||||
assert ctx.selected_wild_card_numbers == ["WC-02"]
|
||||
# 카드 전술 확정 — 설득 카드/읽기 전용 변수는 제안가 없음, WC-02 는 스크립트 파싱으로 중간가.
|
||||
assert ctx.card_specs["NGC-003"]["offer_variable"] is None
|
||||
assert ctx.card_specs["NGC-008"]["offer_variable"] is None # 인터넷 최저가는 읽어주기 변수 — 제안가 아님
|
||||
# 시장가 인용 카드는 최저가 결측 세션에서 미발동하도록 requires 로 표시된다(토큰 노출 방지).
|
||||
assert ctx.card_specs["NGC-008"]["requires"] == ["internet_lowest_price"]
|
||||
assert ctx.card_specs["WC-02"] == {
|
||||
"offer_variable": "target_mid_price", "min_round": 1, "closing": False, "requires": [],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -49,14 +49,9 @@ def test_wildcard_threshold_is_config_driven():
|
||||
# 기본(1.02): anchor 10000, 제시 10800 → 임계 밖 → 일반 가격협상
|
||||
view = _engine().advance(_session(10800), "예")
|
||||
assert view.step == "가격협상"
|
||||
# 임계를 1.10 으로 완화한 테넌트 → 같은 가격에서 1% 인하 와일드카드 발동.
|
||||
# 1%가(10800×0.99=10692)도 제안가 공통 유효조건(≤목표가)을 타므로 목표가를 그 위로 둔다 —
|
||||
# 기본 target(10100)이면 초과 제시 금지 규칙에 걸려 발동하지 않는 게 새 정답.
|
||||
view = _engine(wildcard_1pct_ratio=1.10).advance(_session(10800, target_price=11000), "예")
|
||||
assert view.step == "wild_card_1pct"
|
||||
# 목표가가 1%가 아래면(초과 제시 금지) 완화 임계라도 미발동 — 수락해도 결렬되는 모순 제안 차단.
|
||||
# 임계를 1.10 으로 완화한 테넌트 → 같은 가격에서 1% 인하 와일드카드 발동
|
||||
view = _engine(wildcard_1pct_ratio=1.10).advance(_session(10800), "예")
|
||||
assert view.step == "가격협상"
|
||||
assert view.step == "wild_card_1pct"
|
||||
|
||||
|
||||
def test_max_counter_rounds_is_config_driven():
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
"""협상 불변식 시나리오 하네스 — 실서비스 스택(ChatService + 실 DB 카드)으로 13개 협상을 완주시키고,
|
||||
IMK 가 잡은 두 부류의 사고(같은 카드 반복 · 이상한 금액)가 어떤 흐름에서도 안 나는지 검사한다.
|
||||
|
||||
시나리오별 기대 이벤트(카드가 나간 턴의 step·카드·금액)를 정확히 못박고, 공통 불변식을 전 턴에 건다:
|
||||
· 카드 중복 없음 — 한 협상에서 같은 card_id 2회 발동 금지
|
||||
· 카드 자리 규칙 — 종결 전용(WC-03·05)은 가격협상_카운터에서만, 비종결 와일드는 wild_card_dynamic 에서만
|
||||
· 타결가 ≤ 목표가 — 어떤 성공 경로도 목표가 초과로 안 끝남
|
||||
· 카운터 멘트의 금액 = 수락 시 타결가 (표시가=타결가)
|
||||
"""
|
||||
|
||||
import uuid as _uuid
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from router.v1.chat.protocol import Req_Chat
|
||||
from services.chat_service import ChatService, reset_sessions
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
from tenancy.registry import TenantEngineRegistry
|
||||
from tests.test_card_tactics import _TENANTS_DIR, _cleanup, _seed_quote_session
|
||||
|
||||
# 종결 전용 와일드카드(DB tactic 시드와 동일) — 자리 규칙 검사용.
|
||||
_CLOSING_WILDS = {"WC-03", "WC-05"}
|
||||
_NONCLOSING_WILDS = {"WC-01", "WC-02", "WC-04"}
|
||||
# 카드가 나갈 수 있는 스텝(이벤트로 수집).
|
||||
_CARD_STEPS = {"가격협상", "wild_card_dynamic", "wild_card_1pct", "가격협상_카운터"}
|
||||
_BOILERPLATE = [None, "확인", "예", "확인"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Scenario:
|
||||
name: str
|
||||
inputs: list # 서두(안내~기존가격제시) 이후의 협력사 입력 시퀀스
|
||||
# 기대 이벤트: (step, card, offer_substring). card="NGC-*" 는 임의 협상카드(중복만 검사).
|
||||
events: list
|
||||
settled: Optional[int] # 기대 타결가(원). None=결렬
|
||||
nego: list = field(default_factory=lambda: ["NGC-001"])
|
||||
wild: list = field(default_factory=list)
|
||||
target: int = 10_000
|
||||
anchor: int = 9_900
|
||||
|
||||
|
||||
# 밴드(기본 target 10000·anchor 9900): 1% 존 ≤ 10,098 · 진입 존 ≤ 10,395.
|
||||
SCENARIOS = [
|
||||
# S01 BB9A 재현 — 중반 비종결 WC-02, 종결 WC-05 실절충가. 같은 카드 2회 없음.
|
||||
Scenario("S01_bb9a_mid_wc02_close_wc05",
|
||||
["10300", "예", "다른 가격 제시", "10010", "예", "10005", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-02", "9950"),
|
||||
("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-05", "9980")],
|
||||
settled=9980, wild=["WC-02", "WC-05"]),
|
||||
# S02 8AB0 재현 — 절충가(9,205)가 목표가(9,000) 초과 → WC-05 미발동, 목표가 최후통첩(카드 없음).
|
||||
Scenario("S02_8ab0_middle_over_target_skips",
|
||||
["9500", "예", "9500", "예", "다른 가격 제시", "9500", "예", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", None, "9000")],
|
||||
settled=None, wild=["WC-05"], target=9_000, anchor=8_910),
|
||||
# S03 와일드 5장 전부 + 협상카드 2장 — 중반 1장(WC-01)·종결 1장(WC-03)만, 협상카드는 서로 다른 2장.
|
||||
Scenario("S03_five_wilds_full_run",
|
||||
["10300", "예", "다른 가격 제시", "10200", "예", "10150", "예", "10100", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-01", "10000"),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상_카운터", "WC-03", "10000")],
|
||||
settled=10_000, nego=["NGC-001", "NGC-003"],
|
||||
wild=["WC-01", "WC-02", "WC-03", "WC-04", "WC-05"]),
|
||||
# S04 종결 전용 와일드만 담김 + 제시가가 진입 존에 머무름 — 소진 판정이 막히지 않고
|
||||
# 종결로 넘어간다(프로브 픽스 회귀: 픽스 전엔 빈 덱에서 쓴 카드를 또 꺼내는 무한 협상).
|
||||
Scenario("S04_closing_only_wild_no_deadlock",
|
||||
["10300", "예", "10250", "예", "수락", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", None, "10000")], # WC-05 절충 10,075>목표가 → 미발동 → 최후통첩
|
||||
settled=10_000, wild=["WC-05"]),
|
||||
# S05 1% 존 — 시스템 1% 카드, 수락 시 표시 금액 그대로 타결.
|
||||
Scenario("S05_one_pct_zone_accept",
|
||||
["10050", "예", "예", "확인"],
|
||||
[("wild_card_1pct", None, "9950")],
|
||||
settled=9_950),
|
||||
# S06 앵커 이하 즉시 타결 — 카드 0장.
|
||||
Scenario("S06_priority_match_no_cards",
|
||||
["9800", "예", "확인"],
|
||||
[],
|
||||
settled=9_800),
|
||||
# S07 목표가 초과 고수 → 설득 1장 → 최후통첩 → 결렬.
|
||||
Scenario("S07_hold_high_fails",
|
||||
["11000", "예", "11000", "예", "다른 가격 제시", "11000", "예", "확인"],
|
||||
[("가격협상", "NGC-003", None),
|
||||
("가격협상_카운터", None, "10000")],
|
||||
settled=None, nego=["NGC-003"]),
|
||||
# S08 협상카드 카운터(NGC-010 목표가 제안) 수락 — 협상카드도 카운터 스텝을 쓴다.
|
||||
Scenario("S08_nego_counter_accept",
|
||||
["11000", "예", "수락", "확인"],
|
||||
[("가격협상_카운터", "NGC-010", "10000")],
|
||||
settled=10_000, nego=["NGC-010"]),
|
||||
# S09 min_round=2 — WC-04 는 1라운드 진입 존에서 안 나가고 2라운드에 나간다.
|
||||
Scenario("S09_min_round_two_defers_wc04",
|
||||
["10300", "예", "10200", "예", "수락", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("wild_card_dynamic", "WC-04", "10000")],
|
||||
settled=10_000, wild=["WC-04"]),
|
||||
# S10 종결 체인 폴백 — WC-05 무효(절충 10,175>목표) → 다음 종결 WC-03 발동.
|
||||
Scenario("S10_closing_chain_falls_to_wc03",
|
||||
["10500", "예", "10450", "예", "다른 가격 제시", "10450", "예", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-03", "10000")],
|
||||
settled=None, wild=["WC-05", "WC-03"]),
|
||||
# S11 중반+종결 콤보 — WC-02 중반, 종결은 WC-05 무효 건너뛰고 WC-03. 전 카드 1회씩.
|
||||
Scenario("S11_mid_and_closing_combo",
|
||||
["10300", "예", "다른 가격 제시", "10400", "예", "10350", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-02", "9950"),
|
||||
("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-03", "10000")],
|
||||
settled=10_000, wild=["WC-02", "WC-05", "WC-03"]),
|
||||
# S12 라운드 상한 — 협상카드 3장 각 1회(중복 없음) 후 상한 도달 → 최후통첩 → 결렬.
|
||||
Scenario("S12_round_cap_distinct_nego_cards",
|
||||
["11000", "예", "11000", "예", "11000", "예", "11000", "예", "다른 가격 제시", "11000", "예", "확인"],
|
||||
[("가격협상", "NGC-*", None),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상", "NGC-*", None),
|
||||
("가격협상_카운터", None, "10000")],
|
||||
settled=None, nego=["NGC-001", "NGC-002", "NGC-003", "NGC-004", "NGC-005"]),
|
||||
# S13 재생성 아님·재료 극단 — 앵커 미박제 세션(anchor=target 폴백)에서도 초과 제시·중복 없음.
|
||||
Scenario("S13_anchor_equals_target_fallback",
|
||||
["10300", "예", "10200", "예", "수락", "확인"],
|
||||
[("가격협상", "NGC-001", None),
|
||||
("가격협상_카운터", "WC-03", "10000")], # WC-05 절충 (10000+10200)/2=10100>목표 → 스킵
|
||||
settled=10_000, wild=["WC-05", "WC-03"], anchor=10_000),
|
||||
# S14 역행 금지(IMK 논의 재현) — 절충 카드(9,950) 뒤에 예산 상한 카드(NGC-007, 앵커 9,900)가
|
||||
# 선택돼 있어도 발동하지 않는다(설득 폴백으로도 안 나감). 낼 카드가 없어져 종결(목표가 최후통첩)로.
|
||||
Scenario("S14_no_offer_regression",
|
||||
["10300", "예", "다른 가격 제시", "10200", "예", "수락", "확인"],
|
||||
[("wild_card_dynamic", "WC-02", "9950"),
|
||||
("가격협상_카운터", None, "10000")], # NGC-007 이벤트가 없어야 함(역행 차단)
|
||||
settled=10_000, nego=["NGC-007"], wild=["WC-02"]),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sc", SCENARIOS, ids=[s.name for s in SCENARIOS])
|
||||
async def test_negotiation_invariants(db_engine, sc: Scenario):
|
||||
reset_sessions()
|
||||
sid = _uuid.uuid4()
|
||||
qid, ver_id = await _seed_quote_session(sid, sc.nego, wild_numbers=sc.wild,
|
||||
target=sc.target, anchor=sc.anchor)
|
||||
try:
|
||||
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
|
||||
eng = await reg.get_engine(str(_uuid.uuid4()))
|
||||
svc = ChatService()
|
||||
trace, settled, outcome = [], None, None
|
||||
for ui in [*_BOILERPLATE, *sc.inputs]:
|
||||
r = await svc.chat(eng, Req_Chat(session_id=str(sid), user_input=ui))
|
||||
assert r.result.success is True, f"{sc.name}: 턴 실패 input={ui} msg={r.msg}"
|
||||
trace.append(r)
|
||||
if r.settled_price is not None:
|
||||
settled = r.settled_price
|
||||
if r.chat_end:
|
||||
outcome = r.outcome
|
||||
|
||||
# ── 기대 이벤트(카드/카운터 턴) 정확 일치 ──
|
||||
events = [r for r in trace if r.step in _CARD_STEPS]
|
||||
got = [(r.step, r.card_id) for r in events]
|
||||
assert len(events) == len(sc.events), f"{sc.name}: 이벤트 수 {got} ≠ 기대 {sc.events}"
|
||||
for r, (step, card, offer) in zip(events, sc.events):
|
||||
assert r.step == step, f"{sc.name}: step {r.step} ≠ {step} (전체 {got})"
|
||||
if card == "NGC-*":
|
||||
assert r.card_id and r.card_id.startswith("NGC-"), f"{sc.name}: 협상카드 기대, 실제 {r.card_id}"
|
||||
else:
|
||||
assert r.card_id == card, f"{sc.name}: card {r.card_id} ≠ {card} (전체 {got})"
|
||||
if offer is not None:
|
||||
assert offer in (r.script or ""), f"{sc.name}: 멘트에 금액 {offer} 없음 — {r.script[:80]}"
|
||||
|
||||
# ── 공통 불변식 ──
|
||||
played = [r.card_id for r in events if r.card_id]
|
||||
assert len(played) == len(set(played)), f"{sc.name}: 카드 중복 발동 {played}"
|
||||
for r in events:
|
||||
if r.card_id in _CLOSING_WILDS:
|
||||
assert r.step == "가격협상_카운터", f"{sc.name}: 종결 카드 {r.card_id}가 중반({r.step})에 발동"
|
||||
if r.card_id in _NONCLOSING_WILDS:
|
||||
assert r.step == "wild_card_dynamic", f"{sc.name}: 비종결 와일드 {r.card_id}가 {r.step}에서 발동"
|
||||
|
||||
# ── 결말 ──
|
||||
if sc.settled is None:
|
||||
assert outcome == "failure" and settled is None, f"{sc.name}: 결렬 기대, settled={settled} outcome={outcome}"
|
||||
else:
|
||||
assert outcome == "success", f"{sc.name}: 타결 기대, outcome={outcome}"
|
||||
assert settled == sc.settled, f"{sc.name}: 타결가 {settled} ≠ 기대 {sc.settled}"
|
||||
assert settled <= sc.target, f"{sc.name}: 목표가 초과 타결 {settled} > {sc.target}"
|
||||
finally:
|
||||
await _cleanup(sid, qid, ver_id)
|
||||
@@ -35,7 +35,7 @@ async def test_two_tenants_distinct_engines():
|
||||
assert e1.mapper.get_card_id(0) == "NGC-001"
|
||||
assert e2.mapper.get_card_id(0) == "NGC-B001"
|
||||
# 차원
|
||||
assert e1.state_space_size == 162 and e1.action_space_size == 9 # 카탈로그 9장(NGC-006·009 소프트삭제)
|
||||
assert e1.state_space_size == 162 and e1.action_space_size == 11
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -69,7 +69,7 @@ async def test_unregistered_company_id_auto_onboards():
|
||||
reg = _registry()
|
||||
# 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state).
|
||||
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
|
||||
assert eng.action_space_size == 9 and eng.state_space_size == 162 # DB 카탈로그 9장
|
||||
assert eng.action_space_size == 11 and eng.state_space_size == 162
|
||||
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
|
||||
assert reg.is_registered("imarketkorea") is True
|
||||
# 빈 키만 미등록 → KeyError
|
||||
|
||||
@@ -69,27 +69,27 @@ async def test_cold_start_creates_warmstart_version(db_engine):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_dim_change_migrates_preserving_learning(db_engine):
|
||||
"""카탈로그 카드 수 변경(7→9) 시 학습 보존 마이그레이션 — 겹치는 셀 복사 + 새 카드 fresh."""
|
||||
"""카탈로그 카드 수 변경(9→11) 시 학습 보존 마이그레이션 — 겹치는 셀 복사 + 새 카드 fresh."""
|
||||
import uuid as _uuid
|
||||
cid = str(_uuid.uuid4())
|
||||
# 이 회사 활성 버전을 A=7 로 시드 + 셀 (5,2)=0.9
|
||||
# 이 회사 활성 버전을 A=9 로 시드 + 셀 (5,2)=0.9
|
||||
repo = LearningRepository(cid)
|
||||
vid = await repo.get_or_create_active_version(
|
||||
state_space_size=162, action_space_size=7, learning_rate=0.1, discount_factor=0.95,
|
||||
scope=2, version_name="old_v7")
|
||||
state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95,
|
||||
scope=2, version_name="old_v9")
|
||||
await repo.upsert_cell(vid, state_index=5, action_id=2, q_value=0.9, count=7)
|
||||
|
||||
# 엔진(_base type:db → 카탈로그 9장) 로드 → 7≠9 감지 → 마이그레이션
|
||||
# 엔진(_base type:db → 카탈로그 11장) 로드 → 9≠11 감지 → 마이그레이션
|
||||
eng = await _reg().get_engine(cid)
|
||||
assert eng.action_space_size == 9
|
||||
assert eng.action_space_size == 11
|
||||
policy, new_vid, _ = await QTablePolicyStore.load(eng)
|
||||
assert str(new_vid) != str(vid) # 새 버전
|
||||
assert policy.qtable.q[5, 2] == 0.9 # 기존 학습 보존
|
||||
assert policy.qtable.q[5, 8] == 0.0 # 새 카드(action 8) fresh
|
||||
assert policy.qtable.q[5, 10] == 0.0 # 새 카드(action 10) fresh
|
||||
assert policy.qtable.visits[5, 2] == 7 # 방문수도 보존
|
||||
# 새 버전이 활성 · 차원 11
|
||||
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||
assert str(active.version_id) == str(new_vid) and active.action_space_size == 9
|
||||
assert str(active.version_id) == str(new_vid) and active.action_space_size == 11
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -42,10 +42,7 @@ def test_requote_structure_preserved():
|
||||
for key in ["서비스안내", "가격제안", "배송형태선택", "가격협상_확인", "결과안내", "결과제출", "협상종료"]:
|
||||
assert key in s
|
||||
assert s["배송형태선택"]["next_input_mode"] == "delivery_type"
|
||||
# 리소스 원본은 회사 용어 토큰({label_*}) — 렌더 시 회사 라벨(없으면 기본값)로 치환된다.
|
||||
assert s["배송형태선택"]["input_options"] == [
|
||||
"{label_delivery_type_1}", "{label_delivery_type_2}", "{label_delivery_type_3}",
|
||||
]
|
||||
assert s["배송형태선택"]["input_options"] == ["협력사배송", "지정택배배송", "픽업배송"]
|
||||
|
||||
|
||||
def test_wildcard_present_and_merged():
|
||||
@@ -173,24 +170,3 @@ async def test_resolve_card_script_prefer_db_for_selected_cards(monkeypatch):
|
||||
|
||||
out = await repo.resolve_card_script(1, "2", {"input_price": 10200}, prefer_db=True)
|
||||
assert out == "선택 카드 DB 멘트 **10200원**"
|
||||
|
||||
|
||||
def test_option_label_tokens_rendered():
|
||||
"""검증: 옵션에 회사 용어 토큰({label_delivery_type_*})이 있는 스텝을 정상 렌더·에러 재렌더로 출력.
|
||||
기대결과: 두 경로 모두 버튼 문자열이 기본 라벨(협력사배송 등)로 치환되고 토큰이 남지 않는다."""
|
||||
import os
|
||||
|
||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
|
||||
from tenancy.config_loader import TenantConfigLoader
|
||||
|
||||
tenants = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
|
||||
cfg = TenantConfigLoader(tenants_dir=tenants, cache_ttl_seconds=0).load("_base")
|
||||
engine = ChatEngine(ScriptRepository(cfg, tenants), rq_type="재견적")
|
||||
session = ChatSession(session_id="s", tenant_id="_base", company_id="_base")
|
||||
|
||||
view = engine.render_step(session, "배송형태선택")
|
||||
assert view.input_options == ["협력사배송", "지정택배배송", "픽업배송"]
|
||||
|
||||
# 에러 재렌더(잘못된 입력 등)도 같은 치환을 타야 한다 — raw 옵션이면 토큰이 버튼에 노출된다.
|
||||
err_view = engine._error(session, "다시 선택해 주세요.")
|
||||
assert err_view.input_options == ["협력사배송", "지정택배배송", "픽업배송"]
|
||||
@@ -1,33 +1,18 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional, Tuple
|
||||
from typing import Tuple
|
||||
|
||||
from sqlalchemy import and_, case, cast, func, nulls_last, or_, select, text, update
|
||||
from sqlalchemy import case, cast, func, nulls_last, or_, select, text, update
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import chats, items, quotations, sessions
|
||||
from common.database.model.models import items, quotations, sessions
|
||||
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
|
||||
from common.logger import LOG
|
||||
|
||||
|
||||
# 협상 세션 CRUD. 목록은 세션(negotiation) ⨝ 상품(partner) ⨝ 견적(quotation) 조인으로 만든다.
|
||||
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
|
||||
|
||||
|
||||
def _effective_status():
|
||||
"""표시용 세션 상태. 견적이 마감됐거나 마감시간이 지났으면 협상생성(1)은 더 참여할 수 없으므로 미참여(4)로 본다.
|
||||
|
||||
참여/채팅진입이 진입 시점에 하는 전이(negotiation_service._load_actionable_session, chat_service.init)와 같은 규칙을
|
||||
목록에서는 쓰기 없이 파생으로만 맞춘다. 마감 일괄정리 이후에 만들어진 세션도 '협상 대기'로 남지 않는다.
|
||||
"""
|
||||
ended = or_(quotations.status == QuotationStatus.CLOSED.value, quotations.end_time < func.now())
|
||||
return case(
|
||||
(and_(sessions.status == SessionStatus.CREATED.value, ended), SessionStatus.NOT_PARTICIPATED.value),
|
||||
else_=sessions.status,
|
||||
)
|
||||
|
||||
|
||||
class ISessionCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
|
||||
@@ -54,9 +39,7 @@ class ISessionCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def update_session_reject(
|
||||
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
|
||||
) -> ErrorType:
|
||||
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -64,6 +47,19 @@ class ISessionCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
|
||||
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
|
||||
try:
|
||||
query = select(func.max(quotations.round)).where(quotations.number == number, quotations.deleted == False) # noqa: E712
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, 0
|
||||
top = rows[0][0] if rows and rows[0] else None
|
||||
return ErrorType.SUCCESS, int(top or 0)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
|
||||
pass
|
||||
|
||||
@@ -77,8 +73,7 @@ class SessionCRUD(ISessionCRUD):
|
||||
def __filters(supplier_id, status, qt_type, keyword=None, result=None):
|
||||
conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712
|
||||
if status is not None:
|
||||
# 표시 상태로 필터 — 탭/KPI 카운트가 목록 배지와 어긋나지 않게 파생값을 그대로 쓴다.
|
||||
conds.append(_effective_status() == status)
|
||||
conds.append(sessions.status == status)
|
||||
if qt_type is not None:
|
||||
conds.append(sessions.qt_type == qt_type)
|
||||
# 검색: 견적번호·상품명·상품코드 부분일치(대소문자 무시). items 는 목록/카운트 둘 다 조인돼 있다.
|
||||
@@ -118,7 +113,7 @@ class SessionCRUD(ISessionCRUD):
|
||||
else:
|
||||
# 그룹별로 정렬 방향이 달라, case 로 '자기 그룹 행만 end_time' 을 갖는 키를 만들고
|
||||
# 반대 그룹은 NULL 로 눌러 간섭을 없앤다. status_rank 가 1차 키라 그룹 경계는 항상 유지.
|
||||
actionable = _effective_status().in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
|
||||
actionable = sessions.status.in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
|
||||
status_rank = case((actionable, 0), else_=1)
|
||||
action_order = case((actionable, quotations.end_time), else_=None).asc()
|
||||
done_order = case((~actionable, quotations.end_time), else_=None).desc()
|
||||
@@ -127,7 +122,7 @@ class SessionCRUD(ISessionCRUD):
|
||||
query = (
|
||||
select(
|
||||
sessions.session_id,
|
||||
_effective_status(), # 마감 후 남은 협상생성은 미참여로 내린다
|
||||
sessions.status,
|
||||
sessions.qt_type,
|
||||
sessions.qt_number,
|
||||
quotations.end_time, # qt_end_time = 견적 마감 시각
|
||||
@@ -141,8 +136,6 @@ class SessionCRUD(ISessionCRUD):
|
||||
quotations.round,
|
||||
quotations.preferred_sp_id, # 낙찰자(공급사) — 나와 같으면 낙찰, 다르면 미낙찰
|
||||
sessions.supplier_id, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
|
||||
# 대화 이력 유무 — 종료된 협상의 '결과 보기'(열람) 버튼을 띄울지 판단용. 열 게 없으면 프론트가 감춘다.
|
||||
select(1).where(chats.session_id == sessions.session_id, chats.deleted == False).exists(), # noqa: E712
|
||||
)
|
||||
.join(items, items.item_id == sessions.item_id)
|
||||
.join(quotations, quotations.qt_id == sessions.quotation_id)
|
||||
@@ -219,18 +212,12 @@ class SessionCRUD(ISessionCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def update_session_reject(
|
||||
self, cdb: AsyncSession, session_id, status: int, reject_reason: str, reject_price: Optional[int] = None,
|
||||
) -> ErrorType:
|
||||
async def update_session_reject(self, cdb: AsyncSession, session_id, status: int, reject_reason: str) -> ErrorType:
|
||||
try:
|
||||
values = {"status": status, "reject_reason": reject_reason}
|
||||
# 공급 희망 가격은 채팅 중 거부에서만 들어온다 — 목록 거부는 가격 없이 사유만 남긴다.
|
||||
if reject_price is not None:
|
||||
values["reject_price"] = reject_price
|
||||
query = (
|
||||
update(sessions)
|
||||
.where(sessions.session_id == session_id)
|
||||
.values(**values)
|
||||
.values(status=status, reject_reason=reject_reason)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
@@ -244,8 +231,7 @@ class SessionCRUD(ISessionCRUD):
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, 0
|
||||
# 단일 컬럼 select 는 scalars() 로 내려와 rows 가 값 리스트다(행 튜플이 아님).
|
||||
top = rows[0] if rows else None
|
||||
top = rows[0][0] if rows and rows[0] else None
|
||||
return ErrorType.SUCCESS, int(top or 0)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
|
||||
@@ -50,7 +50,6 @@ class Res_Me(Res_WebPacketProtocol):
|
||||
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). 공급사가 타결 후 입력")
|
||||
guide_notices: list = Field(default_factory=list, description="협상 유의사항 항목(companies.settings.guide_notices). 빈 값이면 포털 기본 문구")
|
||||
|
||||
|
||||
class Res_Logout(Res_WebPacketProtocol):
|
||||
@@ -72,4 +71,4 @@ class Res_HidePopup(Res_WebPacketProtocol):
|
||||
class Res_SessionBranding(Res_WebPacketProtocol):
|
||||
service_name: str = Field("", description="회사 서비스명(companies.settings.branding.service_name). 미설정 시 빈 값")
|
||||
logo_url: str = Field("", description="회사 로고 URL")
|
||||
helpdesk: list = Field(default_factory=list, description="헬프데스크 연락처 줄 목록(companies.settings.branding.helpdesk). 한 줄 = 담당자 한 명")
|
||||
primary_color: str = Field("", description="브랜드 색상(hex)")
|
||||
@@ -21,7 +21,6 @@ class ListItem(WebPacketProtocol):
|
||||
renegotiation_status: int = Field(0, description="현재 재협상 요청 상태(RenegotiationStatus). 요청 이력이 없으면 0")
|
||||
renegotiation_memo: str = Field("", description="담당자 심사 메모(반려 사유). 없으면 빈 문자열")
|
||||
result: int = Field(0, description="공급사 관점 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰, 재협상 대상)")
|
||||
has_chat: bool = Field(False, description="대화 이력 존재 여부 — 종료된 협상(미참여·거부)의 '결과 보기' 노출 판단용")
|
||||
|
||||
|
||||
class Res_SessionList(Res_WebPacketProtocol):
|
||||
@@ -37,8 +36,6 @@ class Res_Participate(Res_WebPacketProtocol):
|
||||
|
||||
class Req_Reject(WebPacketProtocol):
|
||||
reject_reason: str = Field("", max_length=255, description="거부 사유 (단종/품절 프리셋 라벨 또는 직접 입력)")
|
||||
reject_price: Optional[int] = Field(None, description="공급 희망 가격(원). 채팅 중 거부에서만 들어온다 — 목록 거부엔 없음")
|
||||
opinion: Optional[str] = Field(None, max_length=255, description="추가 의견 — sessions.custom.opinion 에 병합")
|
||||
|
||||
|
||||
class Res_Reject(Res_WebPacketProtocol):
|
||||
|
||||
@@ -62,7 +62,7 @@ async def participate(
|
||||
path="/sessions/{session_id}/reject",
|
||||
response_model=Res_Reject,
|
||||
summary="협상 거부",
|
||||
description="세션 참여를 거부하거나 진행 중인 협상을 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유·공급 희망 가격·의견을 저장.",
|
||||
description="세션 참여를 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유를 저장.",
|
||||
)
|
||||
async def reject(
|
||||
session_id: str = Path(description="대상 협상 세션 uuid"),
|
||||
@@ -71,11 +71,7 @@ async def reject(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.reject(
|
||||
user_info, credentials.credentials, session_id, req.reject_reason, req.reject_price, req.opinion,
|
||||
)
|
||||
)
|
||||
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
|
||||
|
||||
|
||||
@router.post(
|
||||
|
||||
@@ -260,7 +260,6 @@ class AuthService:
|
||||
settings = settings or {}
|
||||
res.branding = settings.get("branding") or {}
|
||||
res.session_fields = settings.get("session_fields") or []
|
||||
res.guide_notices = settings.get("guide_notices") or []
|
||||
return res
|
||||
|
||||
async def session_branding(self, session_id: str) -> Res_SessionBranding:
|
||||
@@ -279,7 +278,7 @@ class AuthService:
|
||||
branding = branding or {}
|
||||
res.service_name = branding.get("service_name") or ""
|
||||
res.logo_url = branding.get("logo_url") or ""
|
||||
res.helpdesk = branding.get("helpdesk") or []
|
||||
res.primary_color = branding.get("primary_color") or ""
|
||||
return res
|
||||
|
||||
async def popup_status(self, user_info: UserInfo, access_token: str) -> Res_PopupStatus:
|
||||
|
||||
@@ -227,8 +227,11 @@ class ChatService:
|
||||
)
|
||||
sess.status = SessionStatus.NOT_PARTICIPATED.value
|
||||
|
||||
# 미참여/협상거부 세션도 '결과 보기'로 지난 대화를 열람할 수 있다(중간 이탈·거부로 끝난 건).
|
||||
# 대화 재개는 send() 가 협상중(2)만 허용하므로 여기서 막지 않아도 읽기 전용이다.
|
||||
# 미참여/협상거부 상태는 진입(열람) 불가 (participate/reject 와 동일 규칙).
|
||||
# 위 마감 변환으로 미참여가 된 세션도 여기서 함께 막힌다.
|
||||
if sess.status in (SessionStatus.NOT_PARTICIPATED.value, SessionStatus.REJECTED.value):
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE)
|
||||
return res
|
||||
|
||||
await self._ensure_in_progress(sess, quote)
|
||||
|
||||
@@ -259,24 +262,10 @@ class ChatService:
|
||||
)
|
||||
res.labels = (settings.get("labels") or {}) if _e == ErrorType.SUCCESS and settings else {}
|
||||
|
||||
# 회사가 VAT(vat_yn)를 관리하지 않으면(hidden_fields) 협상 화면 VAT 표기를 숨긴다(값 null → 프론트 라벨 생략).
|
||||
_hidden = (settings.get("hidden_fields") or []) if _e == ErrorType.SUCCESS and settings else []
|
||||
_features = (settings.get("features") or {}) if _e == ErrorType.SUCCESS and settings else {}
|
||||
|
||||
# VAT 표기 — 부가세 전체 통일 회사(features.vat_mode)는 상품 잔존값과 무관하게 'VAT 별도' 고정(False).
|
||||
# 상품별 관리 회사가 vat_yn 을 숨겼으면(구 방식) 표기 자체를 생략한다(값 null → 프론트 라벨 생략).
|
||||
if _features.get("vat_mode") == "unified_excluded":
|
||||
res.item_vat_yn = False
|
||||
elif "vat_yn" in _hidden:
|
||||
if "vat_yn" in _hidden:
|
||||
res.item_vat_yn = None
|
||||
|
||||
# 협상 기준가 — 회사 설정에서 고른 가격 컬럼(features.nego_baseline_field).
|
||||
# agent 의 인하율 멘트(nego_context_crud._resolve_baseline)와 같은 규칙이어야 화면과 멘트가 어긋나지 않는다.
|
||||
_baseline = _features.get("nego_baseline_field")
|
||||
if _baseline not in ("price", "purchase_price"):
|
||||
# 미설정 회사 폴백 — 공급가를 감췄으면 그 회사는 공급가를 관리하지 않는다는 뜻.
|
||||
_baseline = "purchase_price" if ("price" in _hidden and "purchase_price" not in _hidden) else "price"
|
||||
if _baseline == "purchase_price":
|
||||
res.item_price = item.purchase_price or 0
|
||||
return res
|
||||
|
||||
async def _ensure_in_progress(self, sess, quote) -> None:
|
||||
@@ -463,40 +452,24 @@ class ChatService:
|
||||
# 유저 미입력 가격 타결 케이스 — 마지막 유저 제시가와 다를 수 있다).
|
||||
summary = await self._build_summary(sess, quote, item, final_price, turn.settled_price or last_price)
|
||||
|
||||
# 카드 번호(turn.card_id) → UUID 변환. 번호 정본 표기(NGC-/WC- prefix)로 종류를 가르고,
|
||||
# prefix 없는 구번호는 step 휴리스틱 폴백. 1차 조회가 비면 반대 테이블 재조회 —
|
||||
# 종결 전술의 와일드카드는 step 이 '가격협상_카운터'(wild 미시작)라 step 만으론 카드가
|
||||
# 영영 null 로 남았다(사용 카드 통계·화면 누락 원인).
|
||||
# 카드 번호(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:
|
||||
number = str(turn.card_id)
|
||||
if number.startswith("WC"):
|
||||
wild_first = True
|
||||
elif number.startswith("NGC"):
|
||||
wild_first = False
|
||||
else:
|
||||
wild_first = bool(turn.step and turn.step.startswith("wild"))
|
||||
|
||||
async def _lookup(wild: bool):
|
||||
if wild:
|
||||
found = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_wild_card_id_by_number(s, number),
|
||||
)
|
||||
return found, 2
|
||||
found = await DB_SESSION_MNG.execute_lambda(
|
||||
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_nego_card_id_by_number(s, number),
|
||||
lambda s: self.chat_crud.get_wild_card_id_by_number(s, str(turn.card_id)),
|
||||
)
|
||||
return found, 1
|
||||
|
||||
card_uuid, card_type = await _lookup(wild_first)
|
||||
if card_uuid is None:
|
||||
card_uuid, card_type = await _lookup(not wild_first)
|
||||
if card_uuid is None:
|
||||
card_type = None
|
||||
card_type = 2
|
||||
else:
|
||||
card_uuid = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_nego_card_id_by_number(s, str(turn.card_id)),
|
||||
)
|
||||
card_type = 1
|
||||
|
||||
# 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션.
|
||||
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary, card_uuid=card_uuid, card_type=card_type)
|
||||
@@ -637,17 +610,7 @@ class ChatService:
|
||||
# 배송형태: 재견적(CM)의 '배송형태선택' 단계에서 공급사가 고른 라벨. 재협상엔 단계가 없어 None.
|
||||
delivery_label = await self._delivery_choice(sess) if sess.qt_type == 2 else None
|
||||
# 상품 기본 배송유형(코드→라벨). 선택값이 없으면 표시에 폴백으로 쓸 수 있다.
|
||||
# 회사가 배송유형 보기를 자기 용어로 바꿨으면(settings.labels['delivery_type.N']) 그 단어를 쓴다 —
|
||||
# 협상 중 공급사가 고른 보기와 요약 표기가 갈리지 않도록.
|
||||
item_delivery_label = ""
|
||||
if item and item.delivery_type is not None:
|
||||
_e2, _settings = await DB_SESSION_MNG.execute_lambda(
|
||||
suppliers.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_company_settings(s, sess.supplier_id),
|
||||
)
|
||||
_labels = (_settings.get("labels") or {}) if _e2 == ErrorType.SUCCESS and _settings else {}
|
||||
item_delivery_label = (_labels.get(f"delivery_type.{item.delivery_type}")
|
||||
or DeliveryType.label_of(item.delivery_type))
|
||||
item_delivery_label = DeliveryType.label_of(item.delivery_type) if item and item.delivery_type is not None else ""
|
||||
|
||||
def _iso(dt):
|
||||
if dt is None:
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
@@ -183,7 +182,6 @@ class NegotiationService:
|
||||
renegotiation_status=status,
|
||||
renegotiation_memo=renego.get("memo") or "",
|
||||
result=NegotiationService._to_result(r[10], r[11], r[13], r[14]),
|
||||
has_chat=bool(r[15]),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -436,10 +434,7 @@ class NegotiationService:
|
||||
res.session_id = str(sess.session_id)
|
||||
return res
|
||||
|
||||
async def reject(
|
||||
self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str,
|
||||
reject_price: Optional[int] = None, opinion: Optional[str] = None,
|
||||
) -> Res_Reject:
|
||||
async def reject(self, user_info: UserInfo, access_token: str, session_id_str: str, reject_reason: str) -> Res_Reject:
|
||||
res = Res_Reject()
|
||||
|
||||
# 거부 사유 필수
|
||||
@@ -459,19 +454,11 @@ class NegotiationService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 거부 처리 — 세션을 협상거부로 전이하고 사유·공급 희망 가격 저장.
|
||||
# 의견은 부가정보와 같은 custom 컬럼이라 병합(덮어쓰기 금지) — 채팅 결렬 폼과 같은 자리.
|
||||
funcs = [
|
||||
lambda s: self.session_crud.update_session_reject(
|
||||
s, sess.session_id, SessionStatus.REJECTED.value, reason, reject_price,
|
||||
)
|
||||
]
|
||||
note = (opinion or "").strip()[:255]
|
||||
if note:
|
||||
funcs.append(
|
||||
lambda s: self.session_crud.merge_session_custom(s, sess.session_id, sess.supplier_id, {"opinion": note})
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run([sessions.DBType()], funcs)
|
||||
# 거부 처리 — 세션을 협상거부로 전이하고 사유 저장
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.update_session_reject(s, sess.session_id, SessionStatus.REJECTED.value, reason)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
@@ -226,35 +226,6 @@ async def test_chat_init_forbidden_other_supplier(client, chat_seed):
|
||||
assert body["result"]["code"] == 1300 # NEGO_FORBIDDEN
|
||||
|
||||
|
||||
async def test_chat_init_vat_mode_unified_shows_excluded(client, chat_seed, db_engine):
|
||||
"""검증: 부가세 전체 통일 회사(features.vat_mode=unified_excluded)의 세션 채팅 init.
|
||||
기대결과: 상품에 vat_yn=true 잔존값이 있어도 item_vat_yn=False — 프론트가 'VAT별도'로 고정 표기."""
|
||||
import json
|
||||
|
||||
company_id = uuid.uuid4()
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO company.companies (company_id, name, status, settings) VALUES (:c, :n, 1, CAST(:s AS JSONB))"),
|
||||
{"c": company_id, "n": f"{MARK}VAT통일사", "s": json.dumps({"features": {"vat_mode": "unified_excluded"}})},
|
||||
)
|
||||
await conn.execute(
|
||||
text("UPDATE partner.suppliers SET company_id = :c WHERE supplier_id = :sid"),
|
||||
{"c": company_id, "sid": chat_seed["supplier_id"]},
|
||||
)
|
||||
await conn.execute(
|
||||
text("UPDATE partner.items SET vat_yn = true WHERE item_id = (SELECT item_id FROM negotiation.sessions WHERE session_id = :s)"),
|
||||
{"s": chat_seed["sids"]["P"]},
|
||||
)
|
||||
try:
|
||||
token = await _login_token(client)
|
||||
body = (await _init(client, token, chat_seed["sids"]["P"])).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["item_vat_yn"] is False
|
||||
finally:
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("DELETE FROM company.companies WHERE company_id = :c"), {"c": company_id})
|
||||
|
||||
|
||||
# ---- messages (오프닝 seed) -------------------------------------------------
|
||||
async def test_messages_seeds_opening(client, chat_seed):
|
||||
token = await _login_token(client)
|
||||
@@ -380,28 +351,23 @@ async def test_send_blocked_when_prev_turn_pending(client, chat_seed, db_engine)
|
||||
|
||||
|
||||
async def test_init_marks_expired_created_as_not_participated(client, chat_seed, db_engine):
|
||||
"""검증: 마감시간이 지난 협상생성 세션으로 채팅 진입.
|
||||
기대결과: DB 상태가 미참여(4)로 정리되고, init 자체는 열람용으로 성공한다."""
|
||||
token = await _login_token(client)
|
||||
sid, qid = chat_seed["sids"]["C"], chat_seed["qids"]["C"] # 협상생성(1)
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("UPDATE quotation.quotations SET end_time = now() - make_interval(hours => 1) WHERE qt_id = :qid"), {"qid": qid})
|
||||
body = (await _init(client, token, sid)).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["session_status"] == 4
|
||||
assert await _session_status(db_engine, sid) == 4 # DB 도 미참여로 전이
|
||||
# 마감된 협상생성은 DB 상 미참여로 정리되고, 미참여는 진입 불가라 init 은 에러로 막는다.
|
||||
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE
|
||||
assert await _session_status(db_engine, sid) == 4 # DB 는 미참여로 전이됨
|
||||
|
||||
|
||||
async def test_init_allows_viewing_rejected_session(client, chat_seed, db_engine):
|
||||
"""검증: 협상거부(5)로 끝난 세션에 '결과 보기'로 재진입.
|
||||
기대결과: init 성공(열람 허용) — 대화 재개는 send 가 협상중만 허용해 막는다."""
|
||||
async def test_init_blocks_rejected_session(client, chat_seed, db_engine):
|
||||
token = await _login_token(client)
|
||||
sid = chat_seed["sids"]["P"]
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(text("UPDATE negotiation.sessions SET status = 5 WHERE session_id = :sid"), {"sid": sid}) # 협상거부
|
||||
body = (await _init(client, token, sid)).json()
|
||||
assert body["result"]["success"] is True and body["session_status"] == 5
|
||||
assert (await _send(client, token, sid, "네")).json()["result"]["code"] == 1400 # CHAT_NOT_IN_PROGRESS
|
||||
assert body["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE — 거부 세션 진입 차단
|
||||
|
||||
|
||||
# ---- 순수 헬퍼 단위 테스트 (DB 불필요, ChatService @staticmethod) ----------
|
||||
|
||||
@@ -16,35 +16,6 @@ TEST_SUPPLIER_NAME = "파이테스트협상공급사"
|
||||
MARK = "PYTESTNEGO-" # 시드 식별용 prefix (item code / qt number)
|
||||
|
||||
|
||||
async def _seed_case(conn, code, sess_st, qt_type, hrs, quote_st, sup):
|
||||
"""상품·견적·세션 1세트 시드. 코드/견적번호에 MARK prefix 를 달아 cleanup 이 함께 지운다.
|
||||
hrs 는 마감(quotation.end_time)까지의 시간 — 음수면 이미 마감시간이 지난 건. 반환: (session_id, qt_id)."""
|
||||
item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
|
||||
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')"
|
||||
),
|
||||
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"},
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time) "
|
||||
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, :tp, :st, now(), now() + make_interval(hours => :hrs))"
|
||||
),
|
||||
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "tp": qt_type, "st": quote_st, "hrs": hrs},
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, target_price, status, end_time) "
|
||||
"VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, :qtt, 100000, :st, now())"
|
||||
),
|
||||
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st},
|
||||
)
|
||||
return session_id, qt_id
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def nego_seed(db_engine):
|
||||
"""공급사 + 유저 + 세션/견적 3건(본인) + 1건(타 공급사) 시드. 세션/견적 id 를 반환."""
|
||||
@@ -62,11 +33,6 @@ async def nego_seed(db_engine):
|
||||
sids, qids = {}, {}
|
||||
|
||||
async def _cleanup(conn):
|
||||
# 대화는 세션보다 먼저 지운다(세션이 사라지면 대상을 못 고른다).
|
||||
await conn.execute(text(
|
||||
f"DELETE FROM negotiation.chats WHERE session_id IN "
|
||||
f"(SELECT session_id FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%')"
|
||||
))
|
||||
await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'"))
|
||||
await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'"))
|
||||
@@ -86,9 +52,31 @@ async def nego_seed(db_engine):
|
||||
),
|
||||
{"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash},
|
||||
)
|
||||
for spec in specs:
|
||||
code = spec[0]
|
||||
sids[code], qids[code] = await _seed_case(conn, *spec)
|
||||
for code, sess_st, qt_type, hrs, quote_st, sup in specs:
|
||||
item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
|
||||
sids[code], qids[code] = session_id, qt_id
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) "
|
||||
"VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')"
|
||||
),
|
||||
{"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"},
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time) "
|
||||
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, :tp, :st, now(), now() + make_interval(hours => :hrs))"
|
||||
),
|
||||
{"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "tp": qt_type, "st": quote_st, "hrs": hrs},
|
||||
)
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, target_price, status, end_time) "
|
||||
"VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, :qtt, 100000, :st, now())"
|
||||
),
|
||||
{"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st},
|
||||
)
|
||||
|
||||
yield {"supplier_id": supplier_id, "sids": sids, "qids": qids}
|
||||
|
||||
@@ -153,63 +141,6 @@ async def test_list_filter_status(client, nego_seed):
|
||||
assert body["total"] == 1 and body["items"][0]["item_code"] == f"{MARK}B"
|
||||
|
||||
|
||||
async def test_list_shows_closed_quotation_created_session_as_not_participated(client, db_engine, nego_seed):
|
||||
"""검증: 견적이 마감(3)된 뒤에도 세션이 협상생성(1)으로 남아 있는 건(마감 일괄정리 이후 생성 등).
|
||||
기대결과: 목록 상태는 미참여(4) — '협상 대기'로 새지 않고, status=1 필터에서도 빠지고 status=4 필터에 잡힌다."""
|
||||
async with db_engine.begin() as conn:
|
||||
await _seed_case(conn, "CLOSED1", 1, 2, -1, 3, nego_seed["supplier_id"])
|
||||
token = await _login_token(client)
|
||||
|
||||
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CLOSED1")
|
||||
assert listed["session_status"] == 4
|
||||
|
||||
waiting = (await _list(client, token, status=1)).json()
|
||||
assert waiting["total"] == 1 and {i["item_code"] for i in waiting["items"]} == {f"{MARK}A"}
|
||||
assert f"{MARK}CLOSED1" in {i["item_code"] for i in (await _list(client, token, status=4)).json()["items"]}
|
||||
|
||||
|
||||
async def test_list_shows_deadline_passed_created_session_as_not_participated(client, db_engine, nego_seed):
|
||||
"""검증: 견적은 아직 진행중(2)인데 마감시간(end_time)만 지난 협상생성 세션.
|
||||
기대결과: 미참여(4) — 참여/입장이 막히는 건이라 목록도 같은 상태로 보인다(DB 값은 그대로)."""
|
||||
async with db_engine.begin() as conn:
|
||||
session_id, _ = await _seed_case(conn, "OVERDUE", 1, 2, -3, 2, nego_seed["supplier_id"])
|
||||
token = await _login_token(client)
|
||||
|
||||
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}OVERDUE")
|
||||
assert listed["session_status"] == 4
|
||||
assert await _session_status(db_engine, session_id) == 1 # 목록은 파생 표시만, 쓰기는 하지 않는다
|
||||
|
||||
|
||||
async def test_list_marks_stale_round_not_renegotiable(client, db_engine, nego_seed):
|
||||
"""검증: 개찰(결렬) 마감된 1차 견적에 2차가 이미 생성돼 있는 체인.
|
||||
기대결과: renegotiable False — 다음 라운드가 있으면 재협상 요청 대상이 아니다(체인 최대 차수 판정)."""
|
||||
async with db_engine.begin() as conn:
|
||||
await _seed_case(conn, "CHAIN", 3, 2, -2, 3, nego_seed["supplier_id"])
|
||||
await conn.execute(text(
|
||||
f"UPDATE quotation.quotations SET close_reason = 5 WHERE number = '{MARK}CHAIN'"))
|
||||
# 같은 견적번호의 2차 — 번호가 같아야 체인으로 묶인다.
|
||||
await conn.execute(text(
|
||||
"INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, round, start_time, end_time) "
|
||||
f"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '견적 CHAIN 2차', '{MARK}CHAIN', 2, 2, 2, now(), now() + make_interval(hours => 2))"))
|
||||
token = await _login_token(client)
|
||||
listed = next(i for i in (await _list(client, token)).json()["items"] if i["item_code"] == f"{MARK}CHAIN")
|
||||
assert listed["result"] == 3 and listed["renegotiable"] is False
|
||||
|
||||
|
||||
async def test_list_has_chat_flags_sessions_with_history(client, db_engine, nego_seed):
|
||||
"""검증: 대화 이력이 있는 세션과 없는 세션의 has_chat.
|
||||
기대결과: 이력 있는 건만 True — 종료 건의 '결과 보기' 노출이 이 값으로 갈린다."""
|
||||
async with db_engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text("INSERT INTO negotiation.chats (session_id, seq, sender, target_price) VALUES (:sid, 1, 1, 0)"),
|
||||
{"sid": nego_seed["sids"]["C"]},
|
||||
)
|
||||
token = await _login_token(client)
|
||||
by_code = {i["item_code"]: i["has_chat"] for i in (await _list(client, token)).json()["items"]}
|
||||
assert by_code[f"{MARK}C"] is True
|
||||
assert by_code[f"{MARK}A"] is False
|
||||
|
||||
|
||||
async def test_list_filter_qt_type(client, nego_seed):
|
||||
token = await _login_token(client)
|
||||
body = (await _list(client, token, qt_type=2)).json()
|
||||
@@ -385,40 +316,6 @@ async def test_reject_success(client, nego_seed, db_engine):
|
||||
assert status == 5 and reason == "단종 상품입니다" # REJECTED + 사유 저장
|
||||
|
||||
|
||||
async def test_reject_with_price_and_opinion(client, nego_seed, db_engine):
|
||||
# 채팅 내 협상 거부 경로 — 사유 외에 공급 희망 가격과 의견까지 함께 남긴다.
|
||||
token = await _login_token(client)
|
||||
sid = nego_seed["sids"]["B"]
|
||||
r = await client.post(
|
||||
f"/v1/negotiation/sessions/{sid}/reject",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"reject_reason": "품절", "reject_price": 88000, "opinion": "대체품으로 재견적 부탁드립니다"},
|
||||
)
|
||||
assert r.json()["result"]["success"] is True
|
||||
async with db_engine.begin() as conn:
|
||||
row = (await conn.execute(
|
||||
text("SELECT status, reject_reason, reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
|
||||
{"sid": sid},
|
||||
)).first()
|
||||
assert row.status == 5 and row.reject_reason == "품절"
|
||||
assert row.reject_price == 88000
|
||||
assert row.custom["opinion"] == "대체품으로 재견적 부탁드립니다"
|
||||
|
||||
|
||||
async def test_reject_without_price_keeps_null(client, nego_seed, db_engine):
|
||||
# 목록 거부 경로 — 가격이 없으면 reject_price 를 건드리지 않는다.
|
||||
token = await _login_token(client)
|
||||
sid = nego_seed["sids"]["B"]
|
||||
r = await _reject(client, token, sid, "단종")
|
||||
assert r.json()["result"]["success"] is True
|
||||
async with db_engine.begin() as conn:
|
||||
row = (await conn.execute(
|
||||
text("SELECT reject_price, custom FROM negotiation.sessions WHERE session_id = :sid"),
|
||||
{"sid": sid},
|
||||
)).first()
|
||||
assert row.reject_price is None and row.custom is None
|
||||
|
||||
|
||||
async def test_reject_empty_reason(client, nego_seed):
|
||||
token = await _login_token(client)
|
||||
r = await _reject(client, token, nego_seed["sids"]["B"], " ") # 공백만 → 사유 없음
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 116 KiB |
Binary file not shown.
@@ -1,157 +0,0 @@
|
||||
import AppKit
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
|
||||
let output = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "docs/AIO2O-요청사항-반영보고서.pdf"
|
||||
let W: CGFloat = 595, H: CGFloat = 842, M: CGFloat = 42
|
||||
let navy = NSColor(calibratedRed: 0.06, green: 0.08, blue: 0.16, alpha: 1)
|
||||
let ink = NSColor(calibratedRed: 0.11, green: 0.13, blue: 0.18, alpha: 1)
|
||||
let muted = NSColor(calibratedRed: 0.39, green: 0.43, blue: 0.50, alpha: 1)
|
||||
let paper = NSColor(calibratedRed: 0.98, green: 0.985, blue: 0.995, alpha: 1)
|
||||
let line = NSColor(calibratedRed: 0.86, green: 0.88, blue: 0.92, alpha: 1)
|
||||
let purple = NSColor(calibratedRed: 0.48, green: 0.25, blue: 0.92, alpha: 1)
|
||||
let green = NSColor(calibratedRed: 0.08, green: 0.60, blue: 0.37, alpha: 1)
|
||||
let orange = NSColor(calibratedRed: 0.94, green: 0.48, blue: 0.10, alpha: 1)
|
||||
let red = NSColor(calibratedRed: 0.85, green: 0.24, blue: 0.28, alpha: 1)
|
||||
let blue = NSColor(calibratedRed: 0.13, green: 0.39, blue: 0.92, alpha: 1)
|
||||
|
||||
func pr(_ r: CGRect) -> CGRect { CGRect(x: r.minX, y: H-r.maxY, width: r.width, height: r.height) }
|
||||
func font(_ s: CGFloat, _ w: NSFont.Weight = .regular) -> NSFont {
|
||||
NSFont(name: "Apple SD Gothic Neo", size: s) ?? .systemFont(ofSize: s, weight: w)
|
||||
}
|
||||
func style(_ s: CGFloat, _ c: NSColor = ink, _ w: NSFont.Weight = .regular,
|
||||
_ a: NSTextAlignment = .left, _ spacing: CGFloat = 2.5) -> [NSAttributedString.Key:Any] {
|
||||
let p = NSMutableParagraphStyle(); p.alignment = a; p.lineSpacing = spacing; p.lineBreakMode = .byWordWrapping
|
||||
return [.font:font(s,w), .foregroundColor:c, .paragraphStyle:p]
|
||||
}
|
||||
func text(_ t:String,_ r:CGRect,_ s:CGFloat=10,_ c:NSColor=ink,_ w:NSFont.Weight = .regular,
|
||||
_ a:NSTextAlignment = .left,_ spacing:CGFloat=2.5) {
|
||||
NSAttributedString(string:t,attributes:style(s,c,w,a,spacing)).draw(with:pr(r),options:[.usesLineFragmentOrigin,.usesFontLeading])
|
||||
}
|
||||
func box(_ r:CGRect,_ fill:NSColor = .white,_ stroke:NSColor? = line,_ radius:CGFloat=10) {
|
||||
let p=NSBezierPath(roundedRect:pr(r),xRadius:radius,yRadius:radius); fill.setFill(); p.fill()
|
||||
if let stroke { stroke.setStroke(); p.lineWidth=0.8; p.stroke() }
|
||||
}
|
||||
func pill(_ t:String,_ r:CGRect,_ c:NSColor) {
|
||||
box(r,c.withAlphaComponent(0.12),nil,r.height/2)
|
||||
text(t,CGRect(x:r.minX,y:r.minY+4,width:r.width,height:r.height-7),8.2,c,.semibold,.center,1)
|
||||
}
|
||||
func begin(_ ctx:CGContext,_ page:Int,_ title:String) {
|
||||
ctx.beginPDFPage(nil); ctx.saveGState(); NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current=NSGraphicsContext(cgContext:ctx,flipped:false)
|
||||
paper.setFill(); NSBezierPath(rect:pr(CGRect(x:0,y:0,width:W,height:H))).fill()
|
||||
text(title,CGRect(x:M,y:30,width:420,height:16),7.5,muted,.medium)
|
||||
text(String(format:"%02d",page),CGRect(x:W-M-30,y:30,width:30,height:16),8,muted,.medium,.right)
|
||||
let p=NSBezierPath(); p.move(to:CGPoint(x:M,y:31)); p.line(to:CGPoint(x:W-M,y:31))
|
||||
line.setStroke(); p.lineWidth=0.7; p.stroke()
|
||||
}
|
||||
func end(_ ctx:CGContext) {
|
||||
NSGraphicsContext.restoreGraphicsState(); ctx.restoreGState(); ctx.endPDFPage()
|
||||
}
|
||||
func heading(_ n:String,_ t:String,_ sub:String) {
|
||||
pill(n,CGRect(x:M,y:54,width:34,height:24),purple)
|
||||
text(t,CGRect(x:86,y:49,width:465,height:30),21,navy,.bold)
|
||||
text(sub,CGRect(x:M,y:87,width:W-2*M,height:31),9.5,muted,.regular,.left,3)
|
||||
}
|
||||
func statusRow(_ no:String,_ title:String,_ body:String,_ status:String,_ c:NSColor,_ y:CGFloat,_ h:CGFloat=82) {
|
||||
box(CGRect(x:M,y:y,width:W-2*M,height:h),.white,line,9)
|
||||
pill(no,CGRect(x:M+12,y:y+13,width:28,height:20),c)
|
||||
text(title,CGRect(x:M+50,y:y+12,width:338,height:19),10.5,navy,.bold)
|
||||
pill(status,CGRect(x:W-M-102,y:y+12,width:90,height:21),c)
|
||||
text(body,CGRect(x:M+50,y:y+37,width:W-2*M-64,height:h-44),8.8,ink,.regular,.left,2.4)
|
||||
}
|
||||
func metric(_ value:String,_ label:String,_ x:CGFloat,_ c:NSColor) {
|
||||
box(CGRect(x:x,y:435,width:117,height:96),c.withAlphaComponent(0.08),c.withAlphaComponent(0.3),12)
|
||||
text(value,CGRect(x:x+8,y:454,width:101,height:32),25,c,.bold,.center)
|
||||
text(label,CGRect(x:x+8,y:493,width:101,height:20),9,muted,.medium,.center)
|
||||
}
|
||||
|
||||
var media=CGRect(x:0,y:0,width:W,height:H)
|
||||
guard let consumer=CGDataConsumer(url:URL(fileURLWithPath:output) as CFURL),
|
||||
let ctx=CGContext(consumer:consumer,mediaBox:&media,nil) else { fatalError("PDF 생성 실패") }
|
||||
|
||||
// 1. cover
|
||||
begin(ctx,1,"AIO2O · 요청사항 반영 보고서")
|
||||
box(CGRect(x:0,y:0,width:W,height:H),navy,nil,0)
|
||||
pill("IMPLEMENTATION REVIEW",CGRect(x:M,y:112,width:148,height:25),NSColor(calibratedRed:0.42,green:0.78,blue:1,alpha:1))
|
||||
text("AIO2O 테스트 및 요청사항\n반영 결과 보고서",CGRect(x:M,y:166,width:510,height:112),34,.white,.bold,.left,7)
|
||||
text("260727_AIO2O 테스트 및 요청사항.xlsx 기준\n현재 저장소 구현·커밋·검증 캡처 대조",CGRect(x:M,y:310,width:510,height:60),14,NSColor(calibratedWhite:0.78,alpha:1),.regular,.left,7)
|
||||
box(CGRect(x:M,y:435,width:W-2*M,height:176),NSColor.white.withAlphaComponent(0.07),NSColor.white.withAlphaComponent(0.12),16)
|
||||
text("결론",CGRect(x:M+22,y:458,width:460,height:25),13,.white,.bold)
|
||||
text("핵심 업무 흐름은 대부분 구현되었습니다. 견적 목록·상세, 재협상 접수, 목표가 자동계산, 인터넷 최저가, 종료 의견, 결렬폼 통일, VAT 별도 표기, 10원 반올림은 코드 근거가 확인됩니다.\n\n다만 절충안/자동 제안가의 업무 적정성, SG명·유통레벨의 최종 UX, 최저가 VAT 산식은 추가 확인이 필요합니다.",CGRect(x:M+22,y:495,width:W-2*M-44,height:96),11,NSColor(calibratedWhite:0.88,alpha:1),.regular,.left,5)
|
||||
text("작성일 2026.07.31 | 기준 브랜치 feature/negodata | HEAD 775984fe",CGRect(x:M,y:758,width:W-2*M,height:18),8.5,NSColor(calibratedWhite:0.60,alpha:1))
|
||||
end(ctx)
|
||||
|
||||
// 2. summary
|
||||
begin(ctx,2,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("01","종합 요약","엑셀 RAW 시트의 24개 요청을 현재 저장소 상태로 재판정했습니다. 중복 요청은 원 요청 번호를 유지했습니다.")
|
||||
metric("18","완료·반영",M,green); metric("3","부분 반영",M+130,orange); metric("3","확인 필요",M+260,red); metric("24","전체 항목",M+390,blue)
|
||||
text("판정 기준",CGRect(x:M,y:566,width:507,height:24),13,navy,.bold)
|
||||
statusRow("A","완료·반영","사용자 화면과 처리 로직이 모두 확인되거나, 동일 기능을 제공하는 구현 및 검증 캡처가 존재합니다.","18건",green,603,60)
|
||||
statusRow("B","부분 반영","핵심 기능은 있으나 요청한 명칭·선택값·산식 중 일부가 다르거나 배포/운영 확인이 남았습니다.","3건",orange,675,60)
|
||||
statusRow("C","확인 필요","코드는 존재하지만 계산 결과의 업무 적정성을 확정할 수 없거나 요청 산식이 명시적으로 확인되지 않습니다.","3건",red,747,60)
|
||||
end(ctx)
|
||||
|
||||
// 3. system 1
|
||||
begin(ctx,3,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("02","기본 시스템 반영 내역","견적 생성부터 협력사·최저가·협상 화면까지의 공통 요청입니다.")
|
||||
statusRow("01","견적관리 목록·상세/히스토리","견적 목록과 상세 드로어가 있으며, 상세의 채팅 탭·협상카드 탭이 세션 데이터를 연결합니다. 견적번호별 진행/완료 상태와 상세 확인 경로가 마련됐습니다.","완료",green,132)
|
||||
statusRow("02","재협상 접수 및 관리","공급사 포털에서 결렬 건 재협상 요청·철회가 가능하고, 구매자 화면에 재협상 요청 목록·검토 시트·승인/반려 및 알림이 구현됐습니다.","완료",green,226)
|
||||
statusRow("03","MD 제시가 용어·위치·판매가","‘MD’는 ‘구매담당자’로 통일했고 제시가/산정후보를 ‘3. 낙찰기준’으로 이동했습니다. 판매가 설정은 숨김 처리되어 요청 흐름과 일치합니다.","완료",green,320)
|
||||
statusRow("04","목표가 자동 산출","매입가 × (1 − 목표 네고율)로 구매담당자 제시가를 자동 입력합니다. 예: 10,000원, 2% → 9,800원. 프론트 자동계산과 백엔드 가격 처리 근거가 있습니다.","완료",green,414)
|
||||
statusRow("05","공급사/매입가 라벨 일원화","상품 및 견적 화면의 회사별 필드 라벨 설정을 연동해 ‘공급사=매입가’ 표기 정책을 적용할 수 있게 했습니다. 실제 운영 회사 설정값 확인은 필요합니다.","부분",orange,508)
|
||||
statusRow("06","인터넷 최저가 수집","15%에서 멈추던 Worker/큐 처리 문제를 수정하고, 몰별 결과·진행 상태·이력 화면을 재설계했습니다. 다만 요청 산식 ‘(상품가+배송비)/1.1’의 최종 대표값 적용은 코드에서 확정되지 않습니다.","부분",orange,602)
|
||||
statusRow("07","신규 상품 공급사 입력","신규 상품 등록 폼에 공급사 선택기를 추가하고 상품–공급사 매핑을 저장하도록 구현했습니다.","완료",green,696)
|
||||
end(ctx)
|
||||
|
||||
// 4. system 2
|
||||
begin(ctx,4,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("03","협력사·협상 화면 반영","용어 통일, 종료 단계, 가격 표기와 협상 지표를 중심으로 확인했습니다.")
|
||||
statusRow("08","협력사 SG명·유통레벨","취급상품 기반 분류와 공급유형 선택/저장은 구현되어 있습니다. 다만 요청한 SG명 콤보와 유통레벨 4종(제조·총판·대리점·일반유통), 취급상품 삭제가 그대로 완성됐는지는 추가 UX 확인이 필요합니다.","부분",orange,132)
|
||||
statusRow("09","리드타임 → 표준납기","협상 완료 부가정보와 API 설명에 ‘표준납기’가 반영되고 회사 정의 session_fields와 연결됩니다.","완료",green,226)
|
||||
statusRow("10","협상 단가 VAT 별도","협상 상품정보·요약·목록/상세의 단가 표기를 VAT 별도로 통일했습니다. 검증 캡처도 존재합니다.","완료",green,320)
|
||||
statusRow("11","협상 성공률 기준 안내","성공률은 공급사 제시가를 앵커가·목표가와 비교한 1~99 지표입니다. 100% 미달이 결렬 조건은 아니며, 실제 종료는 별도 낙찰/개찰 규칙이 결정합니다.","완료(안내)",blue,414)
|
||||
statusRow("12","협상 종료 추가 의견","타결 부가정보와 결렬 통합폼 모두 ‘기타 의견’을 받으며 sessions.custom.opinion에 저장합니다. 구매자 상세·요약에서 조회되고 완료 후 잠깁니다.","완료",green,508)
|
||||
statusRow("13","결렬 사유·희망가격 통일","기존 RejectRSP/RejectCM을 단일 RejectForm으로 교체했습니다. 결렬사유·희망가·의견을 한 흐름에서 받고 reject_reason/reject_price에 저장합니다.","완료",green,602)
|
||||
statusRow("14","카드 사용 횟수 제한","견적 설정의 card_count(기본 3)를 컨텍스트에서 읽어 실제 사용 가능한 카드 수와 종료 조건을 제한하도록 반영했습니다. 운영 시 기존 세션 회귀검증을 권장합니다.","완료",green,696)
|
||||
end(ctx)
|
||||
|
||||
// 5. case-specific
|
||||
begin(ctx,5,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("04","견적번호별 이슈 반영","EST-202607-05DE·8945·C9D2 사례에서 제기된 가격/종료 흐름을 대조했습니다.")
|
||||
statusRow("15","앵커·자동 제안가 10원 반올림","앵커 생성가, 목표가 후보, 협상카드 카운터를 공통으로 10원 단위 반올림합니다. 예: 15,213원 → 15,210원. 관련 커밋과 단위 테스트가 있습니다.","완료",green,132)
|
||||
statusRow("16","절충안 계산식","협상카드 전술에는 앵커·목표가·직전 제시가를 이용한 중간값 및 목표가 상한 로직이 존재합니다. 다만 ‘절충안’의 기대 공식이 엑셀에 없어 업무적으로 맞는지 확정할 수 없습니다.","확인 필요",red,226)
|
||||
statusRow("17","05DE/C9D2 결렬 희망가격","견적 유형별로 갈리던 결렬 화면을 단일 폼으로 통합해 희망가격 입력 절차를 동일하게 만들었습니다.","완료",green,320)
|
||||
statusRow("18","8945 협상 마무리 개편","종료 후 표준납기·MOQ·발주배수·배송유형 등 회사 정의 부가정보를 선택/입력하고, 기타 의견과 함께 최종 요약에 반영합니다. 배송 선택값은 회사 설정에 따라 구성됩니다.","완료",green,414)
|
||||
statusRow("19","C9D2 자동 제안가 갭","제안가는 카드 전술과 앵커·목표가·직전 제시가의 조합으로 계산되고 10원 반올림됩니다. 17,500원→15,210원의 10.5% 갭이 정책상 적정한지는 목표/앵커 설정을 포함한 별도 검증이 필요합니다.","확인 필요",red,508)
|
||||
statusRow("20","성공/실패 후 의견 조회","협력사가 입력한 종료 의견은 공급사 요약과 구매자 견적 상세 양쪽에서 확인할 수 있고, 종료 후 읽기 전용으로 잠깁니다.","완료",green,602)
|
||||
statusRow("21","중복 요청 통합 반영","엑셀 18/22(성공률), 19/25(종료 의견), 5/23(목표가), 14/17/20(결렬폼)은 각각 하나의 공통 구현으로 해소했습니다.","완료",green,696)
|
||||
end(ctx)
|
||||
|
||||
// 6. evidence
|
||||
begin(ctx,6,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("05","구현 근거","최근 커밋과 현재 코드에서 확인한 핵심 근거입니다. 커밋 단위로 기능 범위를 추적할 수 있습니다.")
|
||||
statusRow("A","b33ae05c · 견적 가격/상품/라벨","목표가 자동입력, 산정후보 위치 이동, 앵커·후보 10원 반올림, 신규 상품 공급사 입력, 회사 설정 라벨 연동.","커밋",purple,132,72)
|
||||
statusRow("B","a56589c6 · 종료폼/의견/VAT","결렬폼 통합, 희망가·사유 저장, 타결/결렬 의견 수취, 상품정보 라벨 연동, 협상 단가 VAT 별도 표기.","커밋",purple,216,72)
|
||||
statusRow("C","30f13483 · 인터넷 최저가","무한 로딩 버그 수정, Worker 설정 보강, 몰별 최저가·진행/상세 UI 및 이력 저장 개선.","커밋",purple,300,72)
|
||||
statusRow("D","9dca78dc · 완료 부가정보","완료 부가정보 수취·요약 표시·잠금, 구매자 상세 노출, VAT 표기 통일.","커밋",purple,384,72)
|
||||
statusRow("E","2a004734 · 견적 상세 연결","견적 상세의 채팅·협상카드 탭 연동과 드로어 탐색 개선.","커밋",purple,468,72)
|
||||
statusRow("F","775984fe / f554202c · 반올림","협상카드 카운터와 자동 앵커를 10원 단위 반올림으로 통일.","커밋",purple,552,72)
|
||||
statusRow("G","화면 검증 캡처","목록/상세, 종료 의견, VAT, 완료 요약, 읽기 전용 잠금 등 12개 캡처가 저장소 루트에 남아 있습니다.","캡처",blue,636,72)
|
||||
text("주의: 본 보고서는 2026-07-31 현재 로컬 저장소의 코드·커밋·캡처를 기준으로 합니다. 운영 배포 여부와 기존 데이터 마이그레이션 상태는 별도 확인 대상입니다.",CGRect(x:M,y:742,width:W-2*M,height:42),8.8,muted,.regular,.left,3)
|
||||
end(ctx)
|
||||
|
||||
// 7. actions
|
||||
begin(ctx,7,"AIO2O · 요청사항 반영 보고서")
|
||||
heading("06","남은 확인 및 권고","기능 누락이라기보다 업무 규칙·운영 설정을 확정해야 하는 항목입니다.")
|
||||
statusRow("1","최저가 VAT 대표값 확정","현재 LPS는 상품가와 배송비를 별도 수집·표시합니다. 대표 최저가를 반드시 (상품가+배송비)/1.1로 저장할지, 화면 표시만 할지 정책을 확정한 뒤 테스트를 추가해야 합니다.","우선순위 높음",red,142,98)
|
||||
statusRow("2","절충안/자동 제안가 기준 검증","05DE·C9D2의 실제 앵커가·목표가·직전 제시가를 넣어 계산 결과를 재현하고, 허용 최대 인하폭 또는 목표가 클램프 기준을 업무 담당자와 합의하는 것이 좋습니다.","우선순위 높음",red,254,98)
|
||||
statusRow("3","SG명·유통레벨 UX 확정","현행 취급상품 기반 분류/공급유형을 요청한 SG 콤보와 유통레벨 4종으로 대체할지, 데이터 모델을 유지한 채 라벨만 조정할지 결정이 필요합니다.","우선순위 중간",orange,366,98)
|
||||
statusRow("4","운영 배포·기존 세션 회귀검증","종료폼, 의견, 카드 횟수 제한은 신규 코드에 반영됐습니다. 운영 컨테이너 재빌드 후 기존 세션과 신규 세션에서 각각 1회 이상 확인해야 합니다.","배포 확인",blue,478,98)
|
||||
box(CGRect(x:M,y:612,width:W-2*M,height:118),purple.withAlphaComponent(0.08),purple.withAlphaComponent(0.28),12)
|
||||
text("권장 최종 승인 기준",CGRect(x:M+18,y:630,width:470,height:22),12,purple,.bold)
|
||||
text("① 운영 배포 버전 확인 ② 대표 견적 3건 시나리오 재실행 ③ 계산식 2건 서면 확정\n④ SG/유통레벨 화면 승인 ⑤ 완료·결렬 의견이 구매자 상세에 저장되는지 확인",CGRect(x:M+18,y:662,width:470,height:50),10,ink,.medium,.left,5)
|
||||
text("— End of report —",CGRect(x:M,y:760,width:W-2*M,height:20),8,muted,.medium,.center)
|
||||
end(ctx)
|
||||
|
||||
ctx.closePDF()
|
||||
Binary file not shown.
@@ -1,790 +0,0 @@
|
||||
import AppKit
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
|
||||
let outPath = CommandLine.arguments.count > 1
|
||||
? CommandLine.arguments[1]
|
||||
: "docs/backend-advanced-concepts-ko.pdf"
|
||||
|
||||
let W: CGFloat = 595
|
||||
let H: CGFloat = 842
|
||||
let margin: CGFloat = 44
|
||||
|
||||
let navy = NSColor(calibratedRed: 0.055, green: 0.086, blue: 0.16, alpha: 1)
|
||||
let ink = NSColor(calibratedRed: 0.10, green: 0.13, blue: 0.18, alpha: 1)
|
||||
let muted = NSColor(calibratedRed: 0.37, green: 0.42, blue: 0.50, alpha: 1)
|
||||
let paper = NSColor(calibratedRed: 0.975, green: 0.98, blue: 0.99, alpha: 1)
|
||||
let line = NSColor(calibratedRed: 0.86, green: 0.88, blue: 0.92, alpha: 1)
|
||||
let blue = NSColor(calibratedRed: 0.16, green: 0.39, blue: 0.93, alpha: 1)
|
||||
let cyan = NSColor(calibratedRed: 0.10, green: 0.69, blue: 0.74, alpha: 1)
|
||||
let green = NSColor(calibratedRed: 0.10, green: 0.63, blue: 0.39, alpha: 1)
|
||||
let orange = NSColor(calibratedRed: 0.94, green: 0.47, blue: 0.12, alpha: 1)
|
||||
let red = NSColor(calibratedRed: 0.88, green: 0.25, blue: 0.28, alpha: 1)
|
||||
let purple = NSColor(calibratedRed: 0.48, green: 0.32, blue: 0.89, alpha: 1)
|
||||
|
||||
func pdfRect(_ r: CGRect) -> CGRect {
|
||||
CGRect(x: r.minX, y: H - r.maxY, width: r.width, height: r.height)
|
||||
}
|
||||
|
||||
func pdfPoint(_ p: CGPoint) -> CGPoint {
|
||||
CGPoint(x: p.x, y: H - p.y)
|
||||
}
|
||||
|
||||
func font(_ size: CGFloat, _ weight: NSFont.Weight = .regular) -> NSFont {
|
||||
NSFont(name: "Apple SD Gothic Neo", size: size)
|
||||
?? NSFont.systemFont(ofSize: size, weight: weight)
|
||||
}
|
||||
|
||||
func mono(_ size: CGFloat) -> NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
|
||||
}
|
||||
|
||||
func attrs(_ size: CGFloat, color: NSColor = ink, weight: NSFont.Weight = .regular,
|
||||
align: NSTextAlignment = .left, lineSpacing: CGFloat = 3) -> [NSAttributedString.Key: Any] {
|
||||
let p = NSMutableParagraphStyle()
|
||||
p.alignment = align
|
||||
p.lineSpacing = lineSpacing
|
||||
p.lineBreakMode = .byWordWrapping
|
||||
return [.font: font(size, weight), .foregroundColor: color, .paragraphStyle: p]
|
||||
}
|
||||
|
||||
func drawText(_ text: String, _ rect: CGRect, size: CGFloat = 11, color: NSColor = ink,
|
||||
weight: NSFont.Weight = .regular, align: NSTextAlignment = .left,
|
||||
lineSpacing: CGFloat = 3) {
|
||||
NSAttributedString(string: text, attributes: attrs(size, color: color, weight: weight,
|
||||
align: align, lineSpacing: lineSpacing))
|
||||
.draw(with: pdfRect(rect), options: [.usesLineFragmentOrigin, .usesFontLeading])
|
||||
}
|
||||
|
||||
func rounded(_ rect: CGRect, radius: CGFloat = 12, fill: NSColor = .white,
|
||||
stroke: NSColor? = line, width: CGFloat = 1) {
|
||||
let p = NSBezierPath(roundedRect: pdfRect(rect), xRadius: radius, yRadius: radius)
|
||||
fill.setFill(); p.fill()
|
||||
if let stroke { stroke.setStroke(); p.lineWidth = width; p.stroke() }
|
||||
}
|
||||
|
||||
func pill(_ text: String, x: CGFloat, y: CGFloat, w: CGFloat, color: NSColor) {
|
||||
rounded(CGRect(x: x, y: y, width: w, height: 25), radius: 12.5,
|
||||
fill: color.withAlphaComponent(0.12), stroke: nil)
|
||||
drawText(text, CGRect(x: x, y: y + 5, width: w, height: 16), size: 9.5,
|
||||
color: color, weight: .semibold, align: .center)
|
||||
}
|
||||
|
||||
func arrow(_ from: CGPoint, _ to: CGPoint, color: NSColor = muted) {
|
||||
let from = pdfPoint(from), to = pdfPoint(to)
|
||||
let p = NSBezierPath(); p.move(to: from); p.line(to: to)
|
||||
color.setStroke(); p.lineWidth = 1.8; p.stroke()
|
||||
let a = atan2(to.y - from.y, to.x - from.x)
|
||||
let l: CGFloat = 7
|
||||
let h = NSBezierPath()
|
||||
h.move(to: to)
|
||||
h.line(to: CGPoint(x: to.x - l * cos(a - .pi / 6), y: to.y - l * sin(a - .pi / 6)))
|
||||
h.line(to: CGPoint(x: to.x - l * cos(a + .pi / 6), y: to.y - l * sin(a + .pi / 6)))
|
||||
h.close(); color.setFill(); h.fill()
|
||||
}
|
||||
|
||||
func node(_ title: String, _ sub: String, rect: CGRect, color: NSColor) {
|
||||
rounded(rect, radius: 10, fill: color.withAlphaComponent(0.10),
|
||||
stroke: color.withAlphaComponent(0.55), width: 1.2)
|
||||
drawText(title, CGRect(x: rect.minX + 8, y: rect.minY + 10, width: rect.width - 16, height: 18),
|
||||
size: 10.5, color: color, weight: .bold, align: .center)
|
||||
drawText(sub, CGRect(x: rect.minX + 8, y: rect.minY + 31, width: rect.width - 16, height: rect.height - 36),
|
||||
size: 8.5, color: muted, align: .center, lineSpacing: 1)
|
||||
}
|
||||
|
||||
func sectionTitle(_ number: String, _ title: String, _ subtitle: String, color: NSColor) {
|
||||
pill(number, x: margin, y: 48, w: 34, color: color)
|
||||
drawText(title, CGRect(x: 86, y: 46, width: 450, height: 30), size: 22,
|
||||
color: navy, weight: .bold)
|
||||
drawText(subtitle, CGRect(x: margin, y: 82, width: W - 2 * margin, height: 26),
|
||||
size: 10.5, color: muted)
|
||||
}
|
||||
|
||||
func footer(_ page: Int, _ label: String = "O2O Negosium · Backend Concepts") {
|
||||
let p = NSBezierPath()
|
||||
p.move(to: CGPoint(x: margin, y: H - 34)); p.line(to: CGPoint(x: W - margin, y: H - 34))
|
||||
line.setStroke(); p.lineWidth = 0.7; p.stroke()
|
||||
drawText(label, CGRect(x: margin, y: H - 28, width: 350, height: 14), size: 7.5, color: muted)
|
||||
drawText("\(page)", CGRect(x: W - margin - 35, y: H - 28, width: 35, height: 14),
|
||||
size: 8, color: muted, align: .right)
|
||||
}
|
||||
|
||||
func callout(_ title: String, _ body: String, rect: CGRect, color: NSColor) {
|
||||
rounded(rect, radius: 12, fill: color.withAlphaComponent(0.08),
|
||||
stroke: color.withAlphaComponent(0.35))
|
||||
rounded(CGRect(x: rect.minX, y: rect.minY, width: 5, height: rect.height),
|
||||
radius: 2.5, fill: color, stroke: nil)
|
||||
drawText(title, CGRect(x: rect.minX + 16, y: rect.minY + 12,
|
||||
width: rect.width - 28, height: 20),
|
||||
size: 11, color: color, weight: .bold)
|
||||
drawText(body, CGRect(x: rect.minX + 16, y: rect.minY + 37,
|
||||
width: rect.width - 28, height: rect.height - 45),
|
||||
size: 9.5, color: ink, lineSpacing: 3)
|
||||
}
|
||||
|
||||
func comparison(_ leftTitle: String, _ left: String, _ rightTitle: String, _ right: String,
|
||||
y: CGFloat, color: NSColor) {
|
||||
let gap: CGFloat = 14
|
||||
let cw = (W - 2 * margin - gap) / 2
|
||||
callout(leftTitle, left, rect: CGRect(x: margin, y: y, width: cw, height: 126), color: red)
|
||||
callout(rightTitle, right, rect: CGRect(x: margin + cw + gap, y: y, width: cw, height: 126), color: color)
|
||||
}
|
||||
|
||||
func codeBox(_ title: String, _ path: String, _ code: String, rect: CGRect, accent: NSColor) {
|
||||
rounded(rect, radius: 10, fill: navy, stroke: nil)
|
||||
drawText(title, CGRect(x: rect.minX + 14, y: rect.minY + 11,
|
||||
width: rect.width - 28, height: 17),
|
||||
size: 10, color: .white, weight: .bold)
|
||||
drawText(path, CGRect(x: rect.minX + 14, y: rect.minY + 30,
|
||||
width: rect.width - 28, height: 14),
|
||||
size: 7.5, color: accent)
|
||||
let p = NSMutableParagraphStyle(); p.lineSpacing = 2; p.lineBreakMode = .byClipping
|
||||
NSAttributedString(string: code, attributes: [.font: mono(7.8), .foregroundColor: NSColor(calibratedWhite: 0.88, alpha: 1), .paragraphStyle: p])
|
||||
.draw(with: pdfRect(CGRect(x: rect.minX + 14, y: rect.minY + 51,
|
||||
width: rect.width - 28, height: rect.height - 60)),
|
||||
options: [.usesLineFragmentOrigin])
|
||||
}
|
||||
|
||||
func beginPage(_ ctx: CGContext, page: Int, label: String = "O2O Negosium · Backend Concepts") {
|
||||
ctx.beginPDFPage(nil)
|
||||
ctx.saveGState()
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current = NSGraphicsContext(cgContext: ctx, flipped: false)
|
||||
paper.setFill(); NSBezierPath(rect: pdfRect(CGRect(x: 0, y: 0, width: W, height: H))).fill()
|
||||
footer(page, label)
|
||||
}
|
||||
|
||||
func endPage(_ ctx: CGContext) {
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
ctx.restoreGState()
|
||||
ctx.endPDFPage()
|
||||
}
|
||||
|
||||
var mediaBox = CGRect(x: 0, y: 0, width: W, height: H)
|
||||
guard let consumer = CGDataConsumer(url: URL(fileURLWithPath: outPath) as CFURL),
|
||||
let ctx = CGContext(consumer: consumer, mediaBox: &mediaBox, nil) else {
|
||||
fatalError("PDF context 생성 실패")
|
||||
}
|
||||
|
||||
// 1 — Cover
|
||||
beginPage(ctx, page: 1, label: "O2O Negosium · Backend Field Guide")
|
||||
rounded(CGRect(x: 0, y: 0, width: W, height: H), radius: 0, fill: navy, stroke: nil)
|
||||
for i in 0..<7 {
|
||||
let x = CGFloat(50 + i * 78)
|
||||
let c = [blue, cyan, green, orange, purple][i % 5]
|
||||
rounded(CGRect(x: x, y: 85 + CGFloat((i % 3) * 28), width: 48, height: 48),
|
||||
radius: 24, fill: c.withAlphaComponent(0.35), stroke: nil)
|
||||
}
|
||||
drawText("BACKEND", CGRect(x: margin, y: 190, width: 507, height: 35), size: 15,
|
||||
color: cyan, weight: .bold)
|
||||
drawText("어려운 개념 5가지,\n코드로 이해하기", CGRect(x: margin, y: 228, width: 507, height: 118),
|
||||
size: 36, color: .white, weight: .bold, lineSpacing: 7)
|
||||
drawText("분산 시스템 · 트랜잭션/동시성 · 멀티테넌시\n캐시 정합성 · 스케줄러/배치",
|
||||
CGRect(x: margin, y: 370, width: 507, height: 62), size: 15,
|
||||
color: NSColor(calibratedWhite: 0.80, alpha: 1), lineSpacing: 8)
|
||||
rounded(CGRect(x: margin, y: 485, width: 507, height: 154), radius: 18,
|
||||
fill: NSColor.white.withAlphaComponent(0.07),
|
||||
stroke: NSColor.white.withAlphaComponent(0.15))
|
||||
drawText("이 문서는 이렇게 읽어요", CGRect(x: 66, y: 510, width: 455, height: 25),
|
||||
size: 14, color: .white, weight: .bold)
|
||||
drawText("① 일상 비유로 개념 잡기\n② 실제 서비스 흐름을 그림으로 보기\n③ 프로젝트 코드에서 구현 확인하기\n④ 없을 때 생기는 문제와 비교하기",
|
||||
CGRect(x: 66, y: 548, width: 455, height: 78), size: 11.5,
|
||||
color: NSColor(calibratedWhite: 0.88, alpha: 1), lineSpacing: 6)
|
||||
drawText("Generated from the current repository · 2026-07-29",
|
||||
CGRect(x: margin, y: 758, width: 507, height: 18), size: 8.5,
|
||||
color: NSColor(calibratedWhite: 0.62, alpha: 1))
|
||||
endPage(ctx)
|
||||
|
||||
// 2 — Architecture map
|
||||
beginPage(ctx, page: 2)
|
||||
drawText("먼저, 서비스 지도를 봅시다", CGRect(x: margin, y: 48, width: 507, height: 34),
|
||||
size: 24, color: navy, weight: .bold)
|
||||
drawText("다섯 개념은 따로 노는 것이 아니라, 한 요청이 여러 서비스와 저장소를 지나면서 함께 작동합니다.",
|
||||
CGRect(x: margin, y: 88, width: 507, height: 32), size: 10.5, color: muted)
|
||||
node("사용자", "브라우저", rect: CGRect(x: 44, y: 170, width: 90, height: 62), color: purple)
|
||||
node("Backend", "채팅·공급사", rect: CGRect(x: 184, y: 145, width: 102, height: 72), color: blue)
|
||||
node("Agent", "AI 협상", rect: CGRect(x: 348, y: 145, width: 102, height: 72), color: orange)
|
||||
node("Negodata", "견적·관리", rect: CGRect(x: 184, y: 270, width: 102, height: 72), color: cyan)
|
||||
node("LPS", "최저가 Worker", rect: CGRect(x: 348, y: 270, width: 102, height: 72), color: green)
|
||||
node("PostgreSQL", "업무 원본", rect: CGRect(x: 184, y: 405, width: 130, height: 72), color: purple)
|
||||
node("Redis", "앵커링 캐시", rect: CGRect(x: 368, y: 405, width: 100, height: 72), color: red)
|
||||
arrow(CGPoint(x: 134, y: 200), CGPoint(x: 184, y: 182), color: purple)
|
||||
arrow(CGPoint(x: 286, y: 180), CGPoint(x: 348, y: 180), color: blue)
|
||||
arrow(CGPoint(x: 235, y: 217), CGPoint(x: 235, y: 270), color: cyan)
|
||||
arrow(CGPoint(x: 286, y: 304), CGPoint(x: 348, y: 304), color: green)
|
||||
arrow(CGPoint(x: 235, y: 342), CGPoint(x: 235, y: 405), color: purple)
|
||||
arrow(CGPoint(x: 399, y: 342), CGPoint(x: 415, y: 405), color: red)
|
||||
callout("① 경계가 생기면 ‘분산 시스템’", "서비스 A가 서비스 B를 네트워크로 호출하는 순간, 지연·타임아웃·부분 실패를 다뤄야 합니다.",
|
||||
rect: CGRect(x: margin, y: 525, width: 246, height: 105), color: blue)
|
||||
callout("② 여러 실행자가 만나면 ‘동시성’", "사용자 클릭과 스케줄러가 같은 견적을 동시에 마감할 수 있어, DB가 최종 심판 역할을 합니다.",
|
||||
rect: CGRect(x: 305, y: 525, width: 246, height: 105), color: orange)
|
||||
callout("③ 빠르게 읽되 원본을 지키면 ‘캐시’", "Redis와 프로세스 메모리는 복사본입니다. PostgreSQL과 설정 파일이 원본입니다.",
|
||||
rect: CGRect(x: margin, y: 650, width: 246, height: 105), color: red)
|
||||
callout("④ 회사별 경계를 지키면 ‘멀티테넌시’", "요청 헤더에서 회사 ID를 결정하고, 회사별 설정·엔진을 선택합니다.",
|
||||
rect: CGRect(x: 305, y: 650, width: 246, height: 105), color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 3 — Distributed systems: concept first
|
||||
beginPage(ctx, page: 3)
|
||||
sectionTitle("3", "분산 시스템 — 개념부터", "여러 독립 실행 단위가 네트워크를 통해 하나의 업무를 완성하는 시스템", color: blue)
|
||||
callout("정확한 정의", "프로세스·컨테이너·서버가 각자 메모리와 실행 상태를 가지고, HTTP나 메시지로 통신하는 구조입니다. 한 서비스의 함수 호출과 달리 상대의 상태를 직접 볼 수 없고, 네트워크 응답만으로 결과를 추론해야 합니다.",
|
||||
rect: CGRect(x: margin, y: 126, width: 507, height: 92), color: blue)
|
||||
drawText("왜 어려운가: 네트워크에는 네 가지 결과가 있습니다", CGRect(x: margin, y: 244, width: 507, height: 24),
|
||||
size: 13.5, color: navy, weight: .bold)
|
||||
let distCases: [(String, String, NSColor)] = [
|
||||
("성공", "상대가 처리했고 응답도 받음", green),
|
||||
("명확한 실패", "상대가 오류 응답을 보냄", red),
|
||||
("연결 실패", "상대에게 요청이 도착하지 않음", orange),
|
||||
("애매한 타임아웃", "처리는 됐지만 응답만 늦었을 수도 있음", purple),
|
||||
]
|
||||
for (i, c) in distCases.enumerated() {
|
||||
let col = i % 2, row = i / 2
|
||||
let x = margin + CGFloat(col) * 260
|
||||
let y = CGFloat(286 + row * 86)
|
||||
callout(c.0, c.1, rect: CGRect(x: x, y: y, width: 247, height: 70), color: c.2)
|
||||
}
|
||||
drawText("대표적인 대응 수단", CGRect(x: margin, y: 475, width: 507, height: 24),
|
||||
size: 13.5, color: navy, weight: .bold)
|
||||
callout("Timeout", "얼마나 기다릴지 상한을 둡니다. 짧으면 정상 요청도 실패하고, 길면 자원이 오래 묶입니다.",
|
||||
rect: CGRect(x: margin, y: 515, width: 159, height: 92), color: blue)
|
||||
callout("Retry", "일시 실패를 다시 시도합니다. 단, 중복 처리에 안전한 작업에서만 제한적으로 사용합니다.",
|
||||
rect: CGRect(x: 218, y: 515, width: 159, height: 92), color: orange)
|
||||
callout("Idempotency", "같은 요청을 여러 번 보내도 결과가 한 번 처리한 것과 같도록 만듭니다.",
|
||||
rect: CGRect(x: 392, y: 515, width: 159, height: 92), color: purple)
|
||||
callout("Fallback", "주 서비스가 실패하면 대체 경로·기본값·이전 데이터를 사용합니다. 대체 결과가 업무적으로 허용될 때만 가능합니다.",
|
||||
rect: CGRect(x: margin, y: 630, width: 247, height: 92), color: green)
|
||||
callout("Circuit breaker", "실패가 계속되는 서비스를 잠시 호출하지 않아 연쇄 장애를 막습니다. 현재 프로젝트에는 명시적 구현이 없습니다.",
|
||||
rect: CGRect(x: 304, y: 630, width: 247, height: 92), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 4 distributed concept
|
||||
beginPage(ctx, page: 4)
|
||||
sectionTitle("3", "분산 시스템과 장애 대응", "한 프로그램이 아니라 여러 서비스가 네트워크로 협력하는 구조", color: blue)
|
||||
callout("쉬운 비유", "한 식당 안에서 주방과 홀 직원이 말로 협업하는 것이 단일 시스템이라면, 분산 시스템은 서로 다른 건물의 팀이 전화로 협업하는 것입니다. 전화는 늦거나 끊길 수 있고, 상대가 일을 끝냈는데 답만 못 받을 수도 있습니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 105), color: blue)
|
||||
drawText("프로젝트의 대표 흐름", CGRect(x: margin, y: 266, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("Backend", "사용자 채팅 요청", rect: CGRect(x: 52, y: 315, width: 110, height: 74), color: blue)
|
||||
node("HTTPX", "timeout 설정", rect: CGRect(x: 242, y: 315, width: 110, height: 74), color: cyan)
|
||||
node("Agent", "협상 턴 계산", rect: CGRect(x: 432, y: 315, width: 110, height: 74), color: orange)
|
||||
arrow(CGPoint(x: 162, y: 352), CGPoint(x: 242, y: 352), color: blue)
|
||||
arrow(CGPoint(x: 352, y: 352), CGPoint(x: 432, y: 352), color: cyan)
|
||||
drawText("성공", CGRect(x: 394, y: 414, width: 80, height: 18), size: 9, color: green, weight: .bold)
|
||||
arrow(CGPoint(x: 485, y: 389), CGPoint(x: 485, y: 458), color: green)
|
||||
node("응답 반영", "채팅 상태 저장", rect: CGRect(x: 430, y: 458, width: 112, height: 65), color: green)
|
||||
drawText("타임아웃/실패", CGRect(x: 185, y: 414, width: 105, height: 18), size: 9, color: red, weight: .bold)
|
||||
arrow(CGPoint(x: 297, y: 389), CGPoint(x: 297, y: 458), color: red)
|
||||
node("안전한 실패", "ok=false 반환", rect: CGRect(x: 241, y: 458, width: 112, height: 65), color: red)
|
||||
callout("중요한 함정: 타임아웃 ≠ 상대가 아무 일도 안 함", "Agent가 DB 상태를 이미 전진시킨 직후 응답만 늦었을 수 있습니다. 그래서 무조건 재시도하면 같은 턴을 두 번 처리할 위험이 있습니다. 코드가 timed_out을 따로 표시하는 이유입니다.",
|
||||
rect: CGRect(x: margin, y: 566, width: 507, height: 105), color: orange)
|
||||
comparison("이 장치가 없으면", "Agent가 느린 순간 Backend 요청도 끝없이 대기합니다. 무작정 재시도하면 협상 step이 두 번 전진할 수 있습니다.",
|
||||
"현재 방식", "HTTP timeout을 두고 성공/일반 실패/타임아웃을 구분합니다. 호출 경계에서 예외를 응답 객체로 변환합니다.",
|
||||
y: 695, color: blue)
|
||||
endPage(ctx)
|
||||
|
||||
// 5 distributed code
|
||||
beginPage(ctx, page: 5)
|
||||
sectionTitle("3", "분산 시스템 — 실제 코드", "서비스 경계마다 timeout, fallback, best-effort 정책이 다릅니다.", color: blue)
|
||||
codeBox("Agent 호출: 타임아웃을 별도 상태로 반환",
|
||||
"backend/services/agent_client.py · lines 81–91",
|
||||
"""
|
||||
async with httpx.AsyncClient(
|
||||
base_url=agent_config.base_url,
|
||||
timeout=agent_config.timeout_sec,
|
||||
) as cli:
|
||||
resp = await cli.post("/v1/chat", json=body, headers=headers)
|
||||
|
||||
except httpx.TimeoutException as ex:
|
||||
# Agent가 이미 처리했을 수 있어 단순 재시도는 위험
|
||||
return AgentTurn(ok=False, timed_out=True)
|
||||
except Exception:
|
||||
return AgentTurn(ok=False)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 245), accent: cyan)
|
||||
codeBox("카탈로그 변경 알림: 핵심 업무를 막지 않는 best-effort",
|
||||
"negodata/backend/services/agent_notify.py · lines 15–26",
|
||||
"""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=3.0) as cli:
|
||||
await cli.post(f"{base}/v1/catalog-refresh-all")
|
||||
except Exception as ex:
|
||||
# 알림 실패는 카드 작업을 막지 않는다
|
||||
LOG.w(f"[agent_notify] 변경 알림 실패(무시): {ex}")
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 395, width: 507, height: 160), accent: green)
|
||||
callout("어떻게 정책을 고르나요?", "결제처럼 반드시 성공해야 하는 작업은 실패를 호출자에게 알려 재처리해야 합니다. 반면 ‘캐시 무효화 알림’처럼 보조적인 작업은 실패해도 핵심 카드 변경을 성공시킬 수 있습니다. 모든 외부 호출을 똑같이 재시도하면 안 됩니다.",
|
||||
rect: CGRect(x: margin, y: 580, width: 507, height: 105), color: blue)
|
||||
drawText("기억할 단어", CGRect(x: margin, y: 712, width: 120, height: 20), size: 12,
|
||||
color: navy, weight: .bold)
|
||||
pill("timeout", x: 150, y: 707, w: 82, color: blue)
|
||||
pill("partial failure", x: 242, y: 707, w: 102, color: orange)
|
||||
pill("best-effort", x: 354, y: 707, w: 92, color: green)
|
||||
pill("idempotency", x: 456, y: 707, w: 90, color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 6 — Transactions and concurrency: concept first
|
||||
beginPage(ctx, page: 6)
|
||||
sectionTitle("4", "트랜잭션·동시성 — 개념부터", "데이터의 일관성을 지키는 작업 단위와, 동시에 실행되는 요청을 제어하는 방법", color: orange)
|
||||
drawText("트랜잭션의 ACID", CGRect(x: margin, y: 126, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let acid: [(String, String, NSColor)] = [
|
||||
("A · Atomicity", "전부 성공하거나 전부 취소", orange),
|
||||
("C · Consistency", "규칙을 만족하는 상태로 이동", green),
|
||||
("I · Isolation", "동시 작업의 중간 상태를 서로 숨김", purple),
|
||||
("D · Durability", "COMMIT된 결과는 장애 후에도 보존", blue),
|
||||
]
|
||||
for (i, a) in acid.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(165 + (i / 2) * 84)
|
||||
callout(a.0, a.1, rect: CGRect(x: x, y: y, width: 247, height: 68), color: a.2)
|
||||
}
|
||||
drawText("동시성 문제는 어떻게 생기나?", CGRect(x: margin, y: 352, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("요청 A", "status=OPEN 읽음", rect: CGRect(x: 48, y: 401, width: 116, height: 64), color: blue)
|
||||
node("요청 B", "status=OPEN 읽음", rect: CGRect(x: 48, y: 500, width: 116, height: 64), color: purple)
|
||||
node("둘 다 처리", "중복 마감·중복 메일", rect: CGRect(x: 250, y: 449, width: 130, height: 70), color: red)
|
||||
arrow(CGPoint(x: 164, y: 433), CGPoint(x: 250, y: 471), color: blue)
|
||||
arrow(CGPoint(x: 164, y: 532), CGPoint(x: 250, y: 497), color: purple)
|
||||
callout("해결 ① 비관적 잠금", "SELECT ... FOR UPDATE로 먼저 행을 잠급니다. 명확하지만 잠금 대기와 deadlock을 관리해야 합니다.",
|
||||
rect: CGRect(x: 408, y: 391, width: 143, height: 92), color: orange)
|
||||
callout("해결 ② 조건부 갱신", "UPDATE ... WHERE status=OPEN 후 rowcount를 확인합니다. 상태 검사와 변경이 원자적으로 일어납니다.",
|
||||
rect: CGRect(x: 408, y: 497, width: 143, height: 92), color: green)
|
||||
callout("격리 수준과 잠금은 만능이 아님", "격리를 높이면 안전성은 커지지만 동시 처리량이 줄고 대기·교착 가능성이 커집니다. 업무 규칙에 맞는 최소 범위의 트랜잭션과 조건부 상태 전이가 실용적입니다.",
|
||||
rect: CGRect(x: margin, y: 624, width: 507, height: 92), color: orange)
|
||||
callout("COMMIT / ROLLBACK", "COMMIT은 변경 확정, ROLLBACK은 현재 트랜잭션의 미확정 변경 취소입니다. 외부 이메일 발송은 DB rollback으로 되돌릴 수 없다는 점도 중요합니다.",
|
||||
rect: CGRect(x: margin, y: 720, width: 507, height: 72), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 7 transaction concept
|
||||
beginPage(ctx, page: 7)
|
||||
sectionTitle("4", "DB 트랜잭션과 동시성 제어", "여러 작업을 하나로 묶고, 동시에 온 요청 중 한 명만 통과시키는 기술", color: orange)
|
||||
callout("트랜잭션이란?", "은행 이체에서 ‘내 계좌 차감’과 ‘상대 계좌 증가’가 둘 다 성공하거나 둘 다 취소되어야 하듯, 관련 DB 변경을 하나의 작업 단위로 묶는 것입니다. 중간에 실패하면 rollback합니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: orange)
|
||||
drawText("동시 마감 문제", CGRect(x: margin, y: 252, width: 200, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("사용자 클릭", "마감 요청 A", rect: CGRect(x: 50, y: 300, width: 110, height: 66), color: blue)
|
||||
node("스케줄러", "마감 요청 B", rect: CGRect(x: 50, y: 405, width: 110, height: 66), color: purple)
|
||||
node("조건부 UPDATE", "status != CLOSED", rect: CGRect(x: 243, y: 350, width: 120, height: 74), color: orange)
|
||||
node("PostgreSQL", "원자적으로 판정", rect: CGRect(x: 430, y: 350, width: 112, height: 74), color: green)
|
||||
arrow(CGPoint(x: 160, y: 333), CGPoint(x: 243, y: 376), color: blue)
|
||||
arrow(CGPoint(x: 160, y: 438), CGPoint(x: 243, y: 399), color: purple)
|
||||
arrow(CGPoint(x: 363, y: 387), CGPoint(x: 430, y: 387), color: orange)
|
||||
callout("승자", "영향받은 행 수(rowcount) = 1\n마감 판정 권한 획득",
|
||||
rect: CGRect(x: 76, y: 518, width: 205, height: 88), color: green)
|
||||
callout("패자/재요청", "rowcount = 0\n이미 닫혔으므로 추가 처리 중단",
|
||||
rect: CGRect(x: 314, y: 518, width: 205, height: 88), color: red)
|
||||
comparison("단순 SELECT 후 UPDATE", "두 요청이 동시에 OPEN을 읽으면 둘 다 마감·낙찰 로직을 실행할 수 있습니다. 이메일도 두 번 발송될 수 있습니다.",
|
||||
"조건부 UPDATE", "DB가 상태 검사와 변경을 한 문장으로 처리합니다. 먼저 성공한 요청만 rowcount=1을 받습니다.",
|
||||
y: 640, color: orange)
|
||||
endPage(ctx)
|
||||
|
||||
// 8 transaction code
|
||||
beginPage(ctx, page: 8)
|
||||
sectionTitle("4", "트랜잭션·동시성 — 실제 코드", "애플리케이션의 if문보다 DB의 원자적 UPDATE가 강한 최종 방어선입니다.", color: orange)
|
||||
codeBox("조건부 상태 전이: 마감 권한 선점",
|
||||
"negodata/backend/crud/quotation_crud.py · lines 482–500",
|
||||
"""
|
||||
query = (
|
||||
update(quotations)
|
||||
.where(
|
||||
quotations.qt_id == qt_id,
|
||||
quotations.status != QuotationStatus.CLOSED.value,
|
||||
quotations.deleted == False,
|
||||
)
|
||||
.values(
|
||||
status=QuotationStatus.CLOSED.value,
|
||||
updated_at=GTime.UTC(),
|
||||
)
|
||||
)
|
||||
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 235), accent: orange)
|
||||
codeBox("트랜잭션 실패 시 rollback",
|
||||
"negodata/backend/common/database/db_session_manager.py · lines 116–127",
|
||||
"""
|
||||
try:
|
||||
await db.commit()
|
||||
return ErrorType.SUCCESS
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
return ErrorType.DB_ALREADY_SAME_KEY
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
raise
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 390, width: 507, height: 175), accent: red)
|
||||
callout("왜 rowcount를 보나요?", "UPDATE가 에러 없이 실행됐다는 사실만으로는 내가 상태를 바꿨는지 알 수 없습니다. WHERE 조건에 맞는 행이 없으면 SQL은 정상 실행되지만 변경 행은 0개입니다. 그래서 1이면 승자, 0이면 이미 다른 요청이 처리한 것으로 판단합니다.",
|
||||
rect: CGRect(x: margin, y: 592, width: 507, height: 108), color: orange)
|
||||
callout("실무 체크", "트랜잭션은 짧게 유지하고, 외부 HTTP·이메일처럼 오래 걸리는 작업을 DB 트랜잭션 안에 오래 붙잡아 두지 않습니다.",
|
||||
rect: CGRect(x: margin, y: 720, width: 507, height: 65), color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 9 — Multitenancy: concept first
|
||||
beginPage(ctx, page: 9)
|
||||
sectionTitle("5", "멀티테넌시 — 개념부터", "하나의 애플리케이션을 여러 고객사가 공유하면서 논리적으로 격리하는 설계", color: purple)
|
||||
callout("Tenant란?", "서비스를 사용하는 독립 고객 단위입니다. 이 프로젝트에서는 주로 ‘회사’가 tenant입니다. 같은 API와 서버를 쓰더라도 회사별 데이터, 설정, 권한, 협상 정책이 섞이면 안 됩니다.",
|
||||
rect: CGRect(x: margin, y: 126, width: 507, height: 88), color: purple)
|
||||
drawText("대표적인 데이터 격리 모델", CGRect(x: margin, y: 242, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
callout("DB 분리", "회사마다 별도 DB\n격리 강함 · 운영비 높음",
|
||||
rect: CGRect(x: margin, y: 282, width: 159, height: 88), color: blue)
|
||||
callout("Schema 분리", "한 DB 안에서 schema 분리\n중간 수준의 격리와 비용",
|
||||
rect: CGRect(x: 218, y: 282, width: 159, height: 88), color: cyan)
|
||||
callout("Row 공유", "같은 테이블 + tenant_id\n효율적 · 쿼리 누락 위험",
|
||||
rect: CGRect(x: 392, y: 282, width: 159, height: 88), color: orange)
|
||||
drawText("격리는 DB만의 문제가 아닙니다", CGRect(x: margin, y: 404, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let tenantAxes: [(String, String)] = [
|
||||
("식별", "이 요청이 어느 회사 것인지 신뢰할 수 있게 결정"),
|
||||
("인가", "그 사용자가 해당 회사 자원에 접근 가능한지 확인"),
|
||||
("데이터", "모든 조회·수정 쿼리에 회사 범위 적용"),
|
||||
("설정", "회사별 정책·브랜딩·카드 선택"),
|
||||
("캐시", "캐시 key에 tenant를 포함해 회사 간 충돌 방지"),
|
||||
("자원", "한 회사의 과부하가 다른 회사에 미치는 영향 제한"),
|
||||
]
|
||||
for (i, t) in tenantAxes.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(444 + (i / 2) * 74)
|
||||
rounded(CGRect(x: x, y: y, width: 247, height: 58), radius: 9,
|
||||
fill: purple.withAlphaComponent(0.06), stroke: purple.withAlphaComponent(0.25))
|
||||
drawText(t.0, CGRect(x: x + 12, y: y + 10, width: 52, height: 18), size: 10,
|
||||
color: purple, weight: .bold)
|
||||
drawText(t.1, CGRect(x: x + 66, y: y + 9, width: 168, height: 38), size: 8.5, color: ink)
|
||||
}
|
||||
callout("가장 흔한 사고", "쿼리의 WHERE tenant_id 조건 누락, 공유 캐시 key에 tenant_id 누락, 사용자가 body로 보낸 tenant_id를 그대로 신뢰하는 경우입니다. 그래서 tenant context를 요청 초기에 확정하고 자동 전달하는 구조가 중요합니다.",
|
||||
rect: CGRect(x: margin, y: 680, width: 507, height: 105), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 10 multitenancy concept
|
||||
beginPage(ctx, page: 10)
|
||||
sectionTitle("5", "멀티테넌시", "하나의 시스템을 여러 회사가 쓰되, 설정과 데이터의 경계를 지키는 구조", color: purple)
|
||||
callout("쉬운 비유", "한 오피스 빌딩을 여러 회사가 함께 사용하지만 출입카드가 자기 회사 층만 열어주는 구조입니다. 서버는 공유하되, 요청마다 ‘어느 회사의 요청인지’를 먼저 확정해야 합니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: purple)
|
||||
drawText("요청이 회사별 엔진을 찾는 과정", CGRect(x: margin, y: 252, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("HTTP 요청", "X-Tenant-ID", rect: CGRect(x: 45, y: 310, width: 100, height: 68), color: blue)
|
||||
node("Middleware", "존재·등록 검증", rect: CGRect(x: 195, y: 310, width: 105, height: 68), color: purple)
|
||||
node("request.state", "tenant_id 보관", rect: CGRect(x: 350, y: 310, width: 105, height: 68), color: cyan)
|
||||
arrow(CGPoint(x: 145, y: 344), CGPoint(x: 195, y: 344), color: blue)
|
||||
arrow(CGPoint(x: 300, y: 344), CGPoint(x: 350, y: 344), color: purple)
|
||||
node("Registry", "회사별 엔진 선택", rect: CGRect(x: 195, y: 445, width: 105, height: 68), color: orange)
|
||||
node("TenantEngine", "회사별 정책·카드", rect: CGRect(x: 350, y: 445, width: 105, height: 68), color: green)
|
||||
arrow(CGPoint(x: 402, y: 378), CGPoint(x: 275, y: 445), color: cyan)
|
||||
arrow(CGPoint(x: 300, y: 479), CGPoint(x: 350, y: 479), color: orange)
|
||||
callout("보안 핵심", "tenant_id를 요청 body에서 받으면 사용자가 다른 회사 ID를 넣어 위조할 수 있습니다. 이 프로젝트는 헤더/경로에서 결정한 값을 middleware가 request.state에 넣고, 뒤의 코드가 그것만 사용합니다.",
|
||||
rect: CGRect(x: margin, y: 558, width: 507, height: 105), color: red)
|
||||
comparison("멀티테넌시 경계가 약하면", "A회사 요청이 B회사 카드·설정·협상 엔진을 사용할 수 있습니다. 이는 단순 버그가 아니라 데이터 유출 사고입니다.",
|
||||
"현재 방식", "요청 시작점에서 tenant를 검증하고, Registry가 해당 회사의 설정과 엔진을 해석합니다.",
|
||||
y: 687, color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 11 multitenancy code
|
||||
beginPage(ctx, page: 11)
|
||||
sectionTitle("5", "멀티테넌시 — 실제 코드", "식별 → 검증 → request.state 전달 → 회사별 엔진 선택의 4단계", color: purple)
|
||||
codeBox("Middleware: tenant를 요청 경계에서 확정",
|
||||
"agent/router/middleware/tenant_middleware.py · lines 35–69",
|
||||
"""
|
||||
tenant_id = request.headers.get("X-Tenant-ID")
|
||||
|
||||
if not tenant_id:
|
||||
return JSONResponse(status_code=400, ...)
|
||||
|
||||
if not tenant_registry.is_registered(tenant_id):
|
||||
return JSONResponse(status_code=404, ...)
|
||||
|
||||
request.state.tenant_id = tenant_id
|
||||
return await call_next(request)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 205), accent: purple)
|
||||
codeBox("Dependency: 검증된 tenant로 엔진 조회",
|
||||
"agent/router/deps.py · lines 13–21",
|
||||
"""
|
||||
async def get_tenant_engine(request: Request) -> TenantEngine:
|
||||
tenant_id = getattr(request.state, "tenant_id", None)
|
||||
if not tenant_id:
|
||||
raise EXCEPTION_TENANT_HEADER_MISSING
|
||||
return await tenant_registry.get_engine(tenant_id)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 360, width: 507, height: 165), accent: cyan)
|
||||
codeBox("Registry: 프로세스 메모리에서 회사별 엔진 재사용",
|
||||
"agent/tenancy/registry.py · lines 85–98",
|
||||
"""
|
||||
cached = self._engines.get(tenant_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
async with self._locks[tenant_id]:
|
||||
cached = self._engines.get(tenant_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
engine = await self._build(tenant_id)
|
||||
self._engines[tenant_id] = engine
|
||||
return engine
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 550, width: 507, height: 205), accent: orange)
|
||||
endPage(ctx)
|
||||
|
||||
// 12 — Cache consistency: concept first
|
||||
beginPage(ctx, page: 12)
|
||||
sectionTitle("8", "캐시 정합성 — 개념부터", "비싼 계산·DB·외부 호출의 결과를 가까운 곳에 복사해 재사용하는 기술", color: red)
|
||||
drawText("기본 용어", CGRect(x: margin, y: 126, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let cacheTerms: [(String, String, NSColor)] = [
|
||||
("Hit", "캐시에 값이 있어 원본을 읽지 않음", green),
|
||||
("Miss", "값이 없어 원본을 읽고 캐시를 채움", blue),
|
||||
("TTL", "값이 자동 만료될 때까지의 시간", orange),
|
||||
("Stale", "원본은 바뀌었지만 캐시는 옛 값인 상태", red),
|
||||
]
|
||||
for (i, t) in cacheTerms.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(165 + (i / 2) * 75)
|
||||
callout(t.0, t.1, rect: CGRect(x: x, y: y, width: 247, height: 60), color: t.2)
|
||||
}
|
||||
drawText("대표적인 읽기·쓰기 패턴", CGRect(x: margin, y: 338, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
callout("Cache-aside", "앱이 캐시를 먼저 조회하고 miss이면 DB를 읽어 캐시에 저장합니다. 단순하고 가장 흔하지만 무효화를 앱이 책임집니다.",
|
||||
rect: CGRect(x: margin, y: 378, width: 247, height: 92), color: blue)
|
||||
callout("Write-through", "쓰기 때 캐시와 원본을 함께 갱신합니다. 읽기는 안정적이지만 쓰기 지연과 두 저장소의 부분 실패를 다뤄야 합니다.",
|
||||
rect: CGRect(x: 304, y: 378, width: 247, height: 92), color: purple)
|
||||
callout("Write-behind", "캐시에 먼저 쓰고 DB는 나중에 반영합니다. 빠르지만 캐시 장애 시 데이터 유실 위험이 있어 업무 원본에는 신중해야 합니다.",
|
||||
rect: CGRect(x: margin, y: 486, width: 247, height: 92), color: orange)
|
||||
callout("Negative cache", "‘결과 없음’도 잠깐 저장합니다. 반복 실패 비용을 줄이지만 너무 긴 TTL은 새로 생긴 데이터를 늦게 발견하게 합니다.",
|
||||
rect: CGRect(x: 304, y: 486, width: 247, height: 92), color: green)
|
||||
drawText("캐시에서 자주 생기는 문제", CGRect(x: margin, y: 610, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
callout("Invalidation", "원본 변경 후 어떤 key를 언제 삭제·갱신할지 결정하기 어렵습니다.",
|
||||
rect: CGRect(x: margin, y: 650, width: 159, height: 82), color: red)
|
||||
callout("Stampede", "인기 key가 만료되는 순간 많은 요청이 동시에 DB로 몰립니다.",
|
||||
rect: CGRect(x: 218, y: 650, width: 159, height: 82), color: orange)
|
||||
callout("Key 설계", "tenant·버전 등이 빠지면 서로 다른 데이터가 같은 key를 공유합니다.",
|
||||
rect: CGRect(x: 392, y: 650, width: 159, height: 82), color: purple)
|
||||
endPage(ctx)
|
||||
|
||||
// 13 cache concept
|
||||
beginPage(ctx, page: 13)
|
||||
sectionTitle("8", "캐시 정합성과 무효화", "빠른 복사본이 원본과 다른 값을 갖지 않도록 관리하는 문제", color: red)
|
||||
callout("캐시는 복사본", "도서관 검색대의 메모가 캐시이고, 원본 장부가 DB라고 생각하면 쉽습니다. 메모는 빠르지만 오래된 정보일 수 있습니다. 정합성이란 메모와 장부가 의미상 같은 상태를 유지하는 것입니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 95), color: red)
|
||||
drawText("앵커링 값의 저장·조회 순서", CGRect(x: margin, y: 252, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("1. DB 저장", "조정 이력 COMMIT", rect: CGRect(x: 46, y: 310, width: 118, height: 70), color: purple)
|
||||
node("2. Redis SET", "최신값 + TTL 7일", rect: CGRect(x: 238, y: 310, width: 118, height: 70), color: red)
|
||||
node("3. 다음 조회", "Redis 우선", rect: CGRect(x: 430, y: 310, width: 118, height: 70), color: blue)
|
||||
arrow(CGPoint(x: 164, y: 345), CGPoint(x: 238, y: 345), color: purple)
|
||||
arrow(CGPoint(x: 356, y: 345), CGPoint(x: 430, y: 345), color: red)
|
||||
drawText("Redis 실패", CGRect(x: 240, y: 417, width: 110, height: 18), size: 9, color: red, weight: .bold)
|
||||
arrow(CGPoint(x: 297, y: 380), CGPoint(x: 297, y: 465), color: red)
|
||||
node("DB Fallback", "업무는 계속", rect: CGRect(x: 238, y: 465, width: 118, height: 70), color: green)
|
||||
callout("stale 데이터란?", "DB에는 새 값 60이 저장됐는데 Redis SET이 실패해 캐시에 옛 값 55가 남은 상태입니다. 캐시 miss와 달리 값이 존재하므로 더 위험합니다. TTL과 주간 re-SET으로 회복합니다.",
|
||||
rect: CGRect(x: margin, y: 574, width: 507, height: 95), color: orange)
|
||||
comparison("캐시만 믿으면", "Redis 장애가 업무 장애가 되고, 오래된 값이 실제 제안가를 왜곡할 수 있습니다. Redis 유실 시 원본도 사라집니다.",
|
||||
"원본 DB + 파생 캐시", "Redis 장애 시 DB를 읽고, TTL과 reconciliation으로 오래된 복사본을 교정합니다.",
|
||||
y: 693, color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 14 cache code
|
||||
beginPage(ctx, page: 14)
|
||||
sectionTitle("8", "캐시 정합성 — 실제 코드", "Cache-aside, TTL, DB fallback, reconciliation이 한 세트로 작동합니다.", color: red)
|
||||
codeBox("Cache-aside: Redis miss → DB → Redis backfill",
|
||||
"schedules/anchoring/src/anchoring/reader.py · lines 33–42",
|
||||
"""
|
||||
cached = await get_value(company_id, supplier_type, price_range)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
value = await get_latest_adjusted_value(
|
||||
db, company_id, supplier_type, price_range
|
||||
)
|
||||
if value is None:
|
||||
value = get_base_anchoring_value(price_range)
|
||||
|
||||
await set_value(..., value, nx=True)
|
||||
return value
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 225), accent: red)
|
||||
codeBox("Redis 장애는 cache miss로 취급",
|
||||
"schedules/anchoring/src/anchoring/redis_client.py · lines 69–84",
|
||||
"""
|
||||
try:
|
||||
raw = await _client.get(anchor_key(...))
|
||||
if raw is None:
|
||||
return None
|
||||
return int(raw)
|
||||
except Exception as ex:
|
||||
_note_failure("get", anchor_key(...), ex)
|
||||
return None # 호출측이 DB fallback
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 380, width: 507, height: 180), accent: orange)
|
||||
callout("두 겹의 회복 장치", "TTL 7일은 오래된 키가 영원히 남는 것을 막습니다. 주간 reconciliation은 DB의 최신 조정값을 Redis에 다시 SET하여, DB commit 뒤 Redis 갱신에 실패했던 값도 교정합니다.",
|
||||
rect: CGRect(x: margin, y: 585, width: 507, height: 100), color: red)
|
||||
callout("현재 견적 생성 경로의 예외", "Negodata의 실제 견적 생성은 Redis를 사용하지 않고 PostgreSQL의 anchoring.current_values View를 일괄 조회합니다. Redis는 현재 anchoring 배치 내부 캐시입니다.",
|
||||
rect: CGRect(x: margin, y: 705, width: 507, height: 72), color: cyan)
|
||||
endPage(ctx)
|
||||
|
||||
// 15 — Scheduler and batch: concept first
|
||||
beginPage(ctx, page: 15)
|
||||
sectionTitle("9", "스케줄러·배치 — 개념부터", "시간 규칙으로 작업을 시작하고, 많은 데이터를 사용자 요청 밖에서 처리하는 방식", color: green)
|
||||
callout("둘의 차이", "스케줄러는 ‘언제 실행할지’를 결정합니다. 배치 Job은 ‘무엇을 어떻게 처리할지’를 구현합니다. CronTrigger가 알람시계라면 close_expired_quotations는 알람이 울렸을 때 수행할 실제 업무입니다.",
|
||||
rect: CGRect(x: margin, y: 126, width: 507, height: 92), color: green)
|
||||
drawText("Job의 생명주기", CGRect(x: margin, y: 248, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("Trigger", "실행 시각 도달", rect: CGRect(x: 45, y: 297, width: 94, height: 66), color: green)
|
||||
node("Select", "처리 대상 조회", rect: CGRect(x: 181, y: 297, width: 94, height: 66), color: blue)
|
||||
node("Process", "개별 업무 수행", rect: CGRect(x: 317, y: 297, width: 94, height: 66), color: orange)
|
||||
node("Checkpoint", "결과·진행점 기록", rect: CGRect(x: 453, y: 297, width: 94, height: 66), color: purple)
|
||||
arrow(CGPoint(x: 139, y: 330), CGPoint(x: 181, y: 330), color: green)
|
||||
arrow(CGPoint(x: 275, y: 330), CGPoint(x: 317, y: 330), color: blue)
|
||||
arrow(CGPoint(x: 411, y: 330), CGPoint(x: 453, y: 330), color: orange)
|
||||
drawText("운영에서 반드시 결정할 것", CGRect(x: margin, y: 405, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
let jobIssues: [(String, String, NSColor)] = [
|
||||
("중복 실행", "이전 Job이 안 끝났는데 다음 시각이 오면?", red),
|
||||
("Misfire", "서버가 꺼져 실행 시각을 놓쳤다면?", orange),
|
||||
("부분 실패", "100건 중 73번째가 실패하면 어디부터 재개?", purple),
|
||||
("재시도", "즉시 재시도, 다음 tick, 운영자 재처리 중 무엇?", blue),
|
||||
("멱등성", "같은 대상을 다시 처리해도 중복 효과가 없는가?", green),
|
||||
("관측성", "처리량·실패 대상·소요시간을 로그와 지표로 남기는가?", cyan),
|
||||
]
|
||||
for (i, j) in jobIssues.enumerated() {
|
||||
let x = margin + CGFloat(i % 2) * 260
|
||||
let y = CGFloat(445 + (i / 2) * 73)
|
||||
callout(j.0, j.1, rect: CGRect(x: x, y: y, width: 247, height: 58), color: j.2)
|
||||
}
|
||||
callout("스케줄러만으로 정확성은 보장되지 않음", "max_instances=1은 한 프로세스 안의 중복을 막을 뿐입니다. 서버가 여러 대면 각 서버가 Job을 실행할 수 있으므로 DB 조건부 갱신, 분산 락, 전용 Worker 같은 추가 방어가 필요합니다.",
|
||||
rect: CGRect(x: margin, y: 680, width: 507, height: 105), color: red)
|
||||
endPage(ctx)
|
||||
|
||||
// 16 scheduler concept
|
||||
beginPage(ctx, page: 16)
|
||||
sectionTitle("9", "스케줄러와 배치 안정성", "사용자 요청 없이 정해진 시간마다 반복 업무를 수행하는 백그라운드 실행", color: green)
|
||||
callout("쉬운 비유", "API가 손님이 주문할 때 움직이는 직원이라면, 스케줄러는 매 5분마다 마감 시간이 지난 주문을 확인하는 당직자입니다. 사람이 요청하지 않아도 시간이 되면 일을 시작합니다.",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 92), color: green)
|
||||
drawText("5분 tick의 세 가지 작업", CGRect(x: margin, y: 252, width: 507, height: 24),
|
||||
size: 14, color: navy, weight: .bold)
|
||||
node("CronTrigger", "매 5분", rect: CGRect(x: 48, y: 315, width: 105, height: 68), color: green)
|
||||
node("잡 ①", "기한 지난 견적 마감", rect: CGRect(x: 225, y: 280, width: 135, height: 62), color: orange)
|
||||
node("잡 ②", "협상 완료 견적 마감", rect: CGRect(x: 225, y: 365, width: 135, height: 62), color: purple)
|
||||
node("잡 ③", "LPS 결과 증분 반영", rect: CGRect(x: 225, y: 450, width: 135, height: 62), color: cyan)
|
||||
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 311), color: green)
|
||||
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 396), color: green)
|
||||
arrow(CGPoint(x: 153, y: 349), CGPoint(x: 225, y: 481), color: green)
|
||||
node("PostgreSQL", "조건부 처리·기록", rect: CGRect(x: 430, y: 365, width: 115, height: 72), color: blue)
|
||||
arrow(CGPoint(x: 360, y: 311), CGPoint(x: 430, y: 385), color: orange)
|
||||
arrow(CGPoint(x: 360, y: 396), CGPoint(x: 430, y: 401), color: purple)
|
||||
arrow(CGPoint(x: 360, y: 481), CGPoint(x: 430, y: 420), color: cyan)
|
||||
callout("중복 실행 방지 장치", "SCHEDULER_ENABLED=1인 프로세스 하나만 잡을 등록합니다. 각 잡은 max_instances=1이고, 밀린 실행은 coalesce=True로 한 번만 실행합니다. 그래도 다중 서버 가능성을 고려해 DB의 조건부 UPDATE가 마지막 방어선입니다.",
|
||||
rect: CGRect(x: margin, y: 565, width: 507, height: 115), color: green)
|
||||
comparison("안정 장치가 없으면", "서버 Worker 수만큼 같은 잡이 실행되고, 같은 견적을 여러 번 마감하거나 알림을 중복 발송할 수 있습니다.",
|
||||
"현재 방식", "실행 프로세스 제한 + 잡 중복 제한 + DB 동시성 가드를 겹쳐 사용합니다.",
|
||||
y: 704, color: green)
|
||||
endPage(ctx)
|
||||
|
||||
// 17 scheduler code
|
||||
beginPage(ctx, page: 17)
|
||||
sectionTitle("9", "스케줄러·배치 — 실제 코드", "‘언제 실행할지’와 ‘무엇을 안전하게 처리할지’를 분리합니다.", color: green)
|
||||
codeBox("APScheduler 등록: 5분, 중복 방지, 지연 허용",
|
||||
"negodata/backend/scheduler/__init__.py · lines 37–69",
|
||||
"""
|
||||
_scheduler = AsyncIOScheduler(timezone="Asia/Seoul")
|
||||
_scheduler.add_job(
|
||||
jobs.close_expired_quotations,
|
||||
CronTrigger(minute="*/5"),
|
||||
id="close_expired_quotations",
|
||||
coalesce=True, # 밀린 실행은 1번만
|
||||
misfire_grace_time=600, # 10분 내 지연 실행 허용
|
||||
max_instances=1, # 같은 잡 동시 실행 금지
|
||||
)
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 130, width: 507, height: 215), accent: green)
|
||||
codeBox("Job: 대상 조회와 개별 마감 처리를 분리",
|
||||
"negodata/backend/scheduler/jobs.py · lines 39–61",
|
||||
"""
|
||||
err_type, qt_ids = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: crud.list_due_for_close(s, now),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return 0
|
||||
|
||||
results = await _close_each(service, qt_ids)
|
||||
return sum(results.values())
|
||||
""",
|
||||
rect: CGRect(x: margin, y: 370, width: 507, height: 190), accent: cyan)
|
||||
callout("멱등성(idempotency)", "같은 잡을 두 번 실행해도 최종 결과가 한 번 실행한 것과 같도록 만드는 성질입니다. 대상 조회가 중복될 수 있어도 claim_for_close의 조건부 UPDATE가 두 번째 처리를 rowcount=0으로 막습니다.",
|
||||
rect: CGRect(x: margin, y: 585, width: 507, height: 105), color: purple)
|
||||
callout("실패한 tick은 어떻게 되나요?", "LPS 동기화는 watermark 기반 증분 처리라 실패한 회차의 데이터가 다음 5분 tick에서 다시 대상이 됩니다. 스케줄러 자체 재시도보다 데이터 설계를 통해 회복합니다.",
|
||||
rect: CGRect(x: margin, y: 710, width: 507, height: 72), color: green)
|
||||
endPage(ctx)
|
||||
|
||||
// 18 combined scenario
|
||||
beginPage(ctx, page: 18)
|
||||
drawText("다섯 기술이 한 장면에서 만나는 순간", CGRect(x: margin, y: 48, width: 507, height: 34),
|
||||
size: 23, color: navy, weight: .bold)
|
||||
drawText("예: 협상이 모두 끝난 견적을 스케줄러가 자동 마감하는 동안 담당자가 수동 마감을 클릭했다.",
|
||||
CGRect(x: margin, y: 88, width: 507, height: 30), size: 10.5, color: muted)
|
||||
let rows: [(String, String, NSColor)] = [
|
||||
("1", "멀티테넌시: 요청의 X-Tenant-ID로 어느 회사의 협상 엔진과 데이터인지 결정", purple),
|
||||
("2", "분산 시스템: Backend가 Agent를 HTTP로 호출할 때 timeout과 부분 실패를 구분", blue),
|
||||
("3", "스케줄러: 5분 tick이 동일 견적을 마감 대상으로 발견", green),
|
||||
("4", "동시성 제어: 수동 요청과 스케줄러 중 조건부 UPDATE를 먼저 성공한 쪽만 처리", orange),
|
||||
("5", "트랜잭션: 관련 상태 변경을 commit하거나, 실패하면 rollback", cyan),
|
||||
("6", "캐시 정합성: 원본 DB commit 후 파생 캐시를 갱신하고 실패 시 다음 회차에 회복", red),
|
||||
]
|
||||
for (i, item) in rows.enumerated() {
|
||||
let y = CGFloat(145 + i * 91)
|
||||
rounded(CGRect(x: margin, y: y, width: 507, height: 70), radius: 12,
|
||||
fill: item.2.withAlphaComponent(0.08), stroke: item.2.withAlphaComponent(0.30))
|
||||
rounded(CGRect(x: 58, y: y + 15, width: 40, height: 40), radius: 20,
|
||||
fill: item.2, stroke: nil)
|
||||
drawText(item.0, CGRect(x: 58, y: y + 24, width: 40, height: 20), size: 13,
|
||||
color: .white, weight: .bold, align: .center)
|
||||
drawText(item.1, CGRect(x: 116, y: y + 15, width: 415, height: 42), size: 10.2,
|
||||
color: ink, weight: .medium, lineSpacing: 3)
|
||||
if i < rows.count - 1 {
|
||||
arrow(CGPoint(x: 78, y: y + 70), CGPoint(x: 78, y: y + 90), color: item.2)
|
||||
}
|
||||
}
|
||||
callout("핵심 관점", "어려운 백엔드 기술은 ‘라이브러리 이름’보다 경계와 실패를 다루는 방법입니다. 네트워크 경계, 회사 경계, 트랜잭션 경계, 캐시의 원본 경계를 명확하게 설계하는 것이 핵심입니다.",
|
||||
rect: CGRect(x: margin, y: 708, width: 507, height: 78), color: navy)
|
||||
endPage(ctx)
|
||||
|
||||
// 19 glossary
|
||||
beginPage(ctx, page: 19)
|
||||
drawText("초보자를 위한 한 줄 사전", CGRect(x: margin, y: 48, width: 507, height: 34),
|
||||
size: 24, color: navy, weight: .bold)
|
||||
let glossary: [(String, String)] = [
|
||||
("분산 시스템", "여러 프로세스·서버가 네트워크로 협력하는 시스템"),
|
||||
("부분 실패", "전체 중 일부 서비스만 실패한 상태"),
|
||||
("Timeout", "응답을 무한히 기다리지 않고 정해진 시간에 포기하는 제한"),
|
||||
("Best-effort", "실패해도 핵심 업무는 성공시키는 보조 작업 정책"),
|
||||
("트랜잭션", "여러 DB 변경을 모두 성공 또는 모두 취소하는 작업 단위"),
|
||||
("Rollback", "실패했을 때 트랜잭션의 변경을 되돌리는 것"),
|
||||
("Race condition", "실행 순서에 따라 결과가 달라지는 동시성 문제"),
|
||||
("원자적 연산", "중간 상태가 보이지 않도록 한 번에 처리되는 연산"),
|
||||
("멀티테넌시", "한 시스템을 여러 고객사가 격리된 상태로 공유하는 구조"),
|
||||
("Cache-aside", "캐시를 먼저 보고, miss이면 원본 조회 후 캐시를 채우는 패턴"),
|
||||
("TTL", "캐시 값이 자동 만료되기까지의 시간"),
|
||||
("Stale", "원본보다 오래되어 현재와 맞지 않는 캐시 상태"),
|
||||
("Invalidation", "원본 변경 시 캐시를 삭제하거나 무효화하는 것"),
|
||||
("Reconciliation", "원본과 복사본을 비교·재적재해 다시 맞추는 작업"),
|
||||
("Scheduler", "정해진 시간 규칙에 따라 작업을 실행하는 도구"),
|
||||
("Batch", "사용자 요청과 별개로 데이터 묶음을 주기적으로 처리하는 작업"),
|
||||
("멱등성", "같은 작업을 반복해도 최종 결과가 달라지지 않는 성질"),
|
||||
]
|
||||
for (i, g) in glossary.enumerated() {
|
||||
let col = i < 9 ? 0 : 1
|
||||
let row = col == 0 ? i : i - 9
|
||||
let x = margin + CGFloat(col) * 260
|
||||
let y = CGFloat(128 + row * 69)
|
||||
drawText(g.0, CGRect(x: x, y: y, width: 230, height: 19), size: 10.5,
|
||||
color: [blue, orange, purple, red, green][i % 5], weight: .bold)
|
||||
drawText(g.1, CGRect(x: x, y: y + 23, width: 230, height: 36), size: 8.8,
|
||||
color: ink, lineSpacing: 2)
|
||||
}
|
||||
callout("추천 복습 순서", "트랜잭션·동시성 → 캐시 정합성 → 스케줄러 → 멀티테넌시 → 분산 시스템 순으로 다시 보면, 작은 DB 작업에서 전체 서비스 구조로 이해가 확장됩니다.",
|
||||
rect: CGRect(x: margin, y: 718, width: 507, height: 74), color: blue)
|
||||
endPage(ctx)
|
||||
|
||||
ctx.closePDF()
|
||||
print(outPath)
|
||||
@@ -57,7 +57,8 @@ export interface RefreshTokenResponse {
|
||||
export interface Branding {
|
||||
service_name?: string
|
||||
logo_url?: string
|
||||
helpdesk?: string[] // 헬프데스크 연락처 — 한 줄 = 담당자 한 명. 비면 연락처 영역을 렌더하지 않는다
|
||||
primary_color?: string
|
||||
email_header?: string
|
||||
}
|
||||
|
||||
// 로그인 전(초청 링크 진입) 브랜딩 조회 — GET /v1/auth/session-branding/{session_id}, 인증 불필요
|
||||
@@ -65,7 +66,7 @@ export interface SessionBrandingResponse {
|
||||
result: ApiResult
|
||||
service_name: string
|
||||
logo_url: string
|
||||
helpdesk?: string[]
|
||||
primary_color: string
|
||||
}
|
||||
|
||||
// 협상완료 부가정보 필드 정의(companies.settings.session_fields)
|
||||
@@ -86,7 +87,6 @@ export interface MeResponse {
|
||||
role: number
|
||||
branding?: Branding
|
||||
session_fields?: SessionField[]
|
||||
guide_notices?: string[]
|
||||
}
|
||||
|
||||
// --- 로그아웃 -------------------------------------------------------------
|
||||
@@ -121,8 +121,6 @@ export interface AuthUser {
|
||||
role: number
|
||||
branding: Branding
|
||||
sessionFields: SessionField[]
|
||||
/** 협상 유의사항 항목(회사 설정). 비면 포털 기본 문구를 쓴다 */
|
||||
guideNotices: string[]
|
||||
}
|
||||
|
||||
export function toAuthUser(res: MeResponse): AuthUser {
|
||||
@@ -135,6 +133,5 @@ export function toAuthUser(res: MeResponse): AuthUser {
|
||||
role: res.role,
|
||||
branding: res.branding ?? {},
|
||||
sessionFields: res.session_fields ?? [],
|
||||
guideNotices: res.guide_notices ?? [],
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,6 @@ export interface SessionListItem {
|
||||
renegotiation_status: number // 1=심사대기 2=승인 3=반려 4=철회, 이력 없으면 0
|
||||
renegotiation_memo: string // 담당자 심사 메모(반려 사유)
|
||||
result: number // 협상 결과(SessionResult): 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
|
||||
has_chat: boolean // 대화 이력 존재 여부 — 종료된 협상의 '결과 보기' 노출 판단용
|
||||
}
|
||||
|
||||
/** 공급사 관점 협상 결과 (sessions 파생) */
|
||||
@@ -119,13 +118,10 @@ export interface ParticipateResponse {
|
||||
}
|
||||
|
||||
// --- 거부 (POST /v1/negotiation/sessions/{id}/reject) ---------------------
|
||||
// 목록의 협상 거부와 채팅 중 협상 거부가 같은 엔드포인트를 쓴다.
|
||||
// reject_reason: 프리셋(단종/품절) 라벨 또는 '기타' 직접 입력 텍스트.
|
||||
// reject_price/opinion: 채팅 중 거부에서만 채운다(목록 거부는 사유만).
|
||||
// (백엔드 sessions.reject_reason 컬럼에 대응. 엔드포인트는 백엔드 추가 예정)
|
||||
export interface RejectRequest {
|
||||
reject_reason: string
|
||||
reject_price?: number
|
||||
opinion?: string
|
||||
}
|
||||
|
||||
export interface RejectResponse {
|
||||
|
||||
@@ -43,9 +43,9 @@ export function usePreLoginBranding(): Branding | null {
|
||||
const next: Branding = {
|
||||
service_name: res.service_name || undefined,
|
||||
logo_url: res.logo_url || undefined,
|
||||
helpdesk: res.helpdesk?.length ? res.helpdesk : undefined,
|
||||
primary_color: res.primary_color || undefined,
|
||||
}
|
||||
if (!next.service_name && !next.logo_url && !next.helpdesk) return
|
||||
if (!next.service_name && !next.logo_url) return
|
||||
setBranding(next)
|
||||
writeCached(next) // 다음 진입에 session_id 가 없어도 이 회사로 보이게 한다
|
||||
})
|
||||
|
||||
@@ -1,33 +1,10 @@
|
||||
import { useState } from 'react'
|
||||
import { SessionStatus } from '@/apis'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { ChatMessage } from '@/features/chat/components/ChatMessage'
|
||||
import { UserButton } from '@/features/chat/components/UserButton'
|
||||
import { RejectPopup } from '@/features/chat/components/popup/RejectPopup'
|
||||
import { canRejectNegotiation, GO_TO_LIST_TEXT } from '@/features/chat/lib/userButtonConfig'
|
||||
import { MobileStepBar } from '@/features/chat/components/MobileStepBar'
|
||||
import type { UserButtonConfig } from '@/features/chat/types'
|
||||
|
||||
// 미참여·협상거부로 끝난 세션은 '결과 보기'(열람) 진입이라 입력을 잠근다.
|
||||
// 마지막 봇 메시지가 입력을 요구하는 상태로 멈춰 있어도(중간 이탈) 서버가 전송을 막으므로 액션바는 복귀 버튼만 둔다.
|
||||
const READ_ONLY_STATUSES: number[] = [SessionStatus.NOT_PARTICIPATED, SessionStatus.REJECTED]
|
||||
const READ_ONLY_CONFIG: UserButtonConfig = { type: 'one-black', text: GO_TO_LIST_TEXT }
|
||||
|
||||
// 거부 가능한 세션 상태 — 백엔드 /reject 가 허용하는 범위(완료/미참여/거부는 불가)와 같다.
|
||||
const REJECTABLE_STATUSES: number[] = [SessionStatus.CREATED, SessionStatus.IN_PROGRESS]
|
||||
|
||||
export function ChatSection() {
|
||||
const { messages, userButtonConfig } = useChatStore()
|
||||
const sessionStatus = useChatInitStore((s) => s.session_status)
|
||||
const [isRejectOpen, setIsRejectOpen] = useState(false)
|
||||
|
||||
const isReadOnly = READ_ONLY_STATUSES.includes(sessionStatus)
|
||||
const config = isReadOnly ? READ_ONLY_CONFIG : userButtonConfig
|
||||
// 단종·품절처럼 대화로 풀 수 없는 사유는 봇의 결렬 선언을 기다릴 수 없다 — 진행 중에도 빠져나갈 길을 둔다.
|
||||
const canReject =
|
||||
!isReadOnly && REJECTABLE_STATUSES.includes(sessionStatus) && canRejectNegotiation(messages, userButtonConfig)
|
||||
|
||||
const { userButtonConfig } = useChatStore()
|
||||
return (
|
||||
<div className="flex flex-1 flex-col w-full h-full min-h-0 bg-surface">
|
||||
<MobileStepBar />
|
||||
@@ -35,9 +12,8 @@ export function ChatSection() {
|
||||
{/* 하단 액션 덱 */}
|
||||
{/* safe-b: 홈 인디케이터에 입력 버튼이 가리지 않도록 하단 안전영역 확보 */}
|
||||
<div className="shrink-0 safe-b border-t border-border bg-white shadow-[0_-4px_20px_rgba(0,0,0,0.03)]">
|
||||
<UserButton {...config} onReject={canReject ? () => setIsRejectOpen(true) : undefined} />
|
||||
<UserButton {...userButtonConfig} />
|
||||
</div>
|
||||
{isRejectOpen && <RejectPopup onClose={() => setIsRejectOpen(false)} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -110,8 +110,7 @@ function ItemInfo() {
|
||||
<div className="flex flex-1 items-start self-stretch overflow-y-auto overflow-x-hidden px-6 min-h-0">
|
||||
<div className="flex flex-col items-start self-stretch flex-1 gap-2 min-w-0">
|
||||
{renderRow(fieldLabel('item.code', '상품코드'), item_code)}
|
||||
{/* 값은 회사가 고른 협상 기준가(item_price), 호칭은 공급사 화면 고정 용어 — 회사 용어 사전을 타지 않는다. */}
|
||||
{renderRow('공급가', formattedPrice)}
|
||||
{renderRow(fieldLabel('item.price', '단가'), formattedPrice)}
|
||||
{renderRow(fieldLabel('item.model_name', '모델명'), item_model_name)}
|
||||
{renderRow(fieldLabel('item.manufacturer', '제조사'), item_maker_name)}
|
||||
{renderRow(fieldLabel('item.moq', '최소주문수량'), item_min_order_quantity)}
|
||||
|
||||
@@ -17,8 +17,7 @@ const style = {
|
||||
'flex min-w-[120px] px-[28px] max-[1180px]:min-w-[100px] max-[1180px]:px-[20px] h-[46px] bg-white hover:bg-neutral-10 rounded-xl items-center justify-center text-sm font-bold text-neutral-80 border border-border cursor-pointer whitespace-nowrap transition-all ease-out active:scale-[0.98]',
|
||||
}
|
||||
|
||||
// onReject: 협상 거부 진입점. 넘어오면 버튼 덱 끝에 붙는다(입력 단계는 인풋이 넓어 좁은 화면에서 아랫줄로 wrap).
|
||||
export function UserButton({ type, text, textList, priceErrorMessage, onReject }: UserButtonConfig & { onReject?: () => void }) {
|
||||
export function UserButton({ type, text, textList, priceErrorMessage }: UserButtonConfig) {
|
||||
if (type === '') return null
|
||||
|
||||
// 부가정보 입력은 폼이라 가운데정렬 덱이 아니라 전체폭으로 편다. text = 저장 후 보낼 동의 문구.
|
||||
@@ -42,13 +41,8 @@ export function UserButton({ type, text, textList, priceErrorMessage, onReject }
|
||||
// 입력 단계는 에러 말풍선이 위로 삐져나가야 해서 overflow 클리핑 제외 (버튼 덱만 가로 스크롤 허용)
|
||||
const isInputStep = type === 'percent' || type === 'price'
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex w-full flex-wrap items-center justify-center gap-3 px-6 py-4 max-[1180px]:px-4',
|
||||
!isInputStep && 'overflow-x-auto',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<div className={cn('flex w-full justify-center px-6 py-4 max-[1180px]:px-4', !isInputStep && 'overflow-x-auto')}>
|
||||
<div className="flex justify-center">
|
||||
{type === 'one-black' && <OneBlack text={text || '확인'} />}
|
||||
{type === 'one-gray' && <OneGray text={text || '확인'} />}
|
||||
{type === 'black-white' && <BlackWhite textList={[textList?.[0] || '예', textList?.[1] || '아니오']} />}
|
||||
@@ -59,19 +53,6 @@ export function UserButton({ type, text, textList, priceErrorMessage, onReject }
|
||||
{type === 'price' && <Price priceErrorMessage={priceErrorMessage} />}
|
||||
{type === 'loading' && <LoadingDots />}
|
||||
</div>
|
||||
{/* 오클릭 방지: 주 CTA 와 붙이지 않는다. 넓은 화면은 우측 끝 고정(가운데 CTA 는 그대로),
|
||||
좁은 화면은 인풋 폭 때문에 같은 줄이 안 나오므로 wrap 되어 아랫줄로 내려간다. */}
|
||||
{onReject && (
|
||||
<button
|
||||
className={cn(
|
||||
style.white,
|
||||
'min-[1180px]:absolute min-[1180px]:right-8 min-[1180px]:top-1/2 min-[1180px]:-translate-y-1/2',
|
||||
)}
|
||||
onClick={onReject}
|
||||
>
|
||||
협상 거부
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import { useMeQuery } from '@/apis'
|
||||
|
||||
// 헬프데스크 — 연락처. (안내 팝업 진입은 상단 '유의사항 및 이용방법' 섹션으로 일원화)
|
||||
// 연락처는 회사 설정(companies.settings.branding.helpdesk)에서 온다. 미등록이면 섹션 자체를 숨긴다.
|
||||
export function Contact() {
|
||||
const { data: user } = useMeQuery()
|
||||
const helpdesk = user?.branding?.helpdesk ?? []
|
||||
if (helpdesk.length === 0) return null
|
||||
|
||||
return (
|
||||
<section className="w-full pt-4">
|
||||
<div className="border-b border-border pb-2">
|
||||
<span className="text-[11px] font-bold tracking-wide text-neutral-60">헬프데스크</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 pt-3 text-sm text-neutral-60">
|
||||
{helpdesk.map((line) => (
|
||||
<span key={line}>{line}</span>
|
||||
))}
|
||||
<span>010-0000-0000</span>
|
||||
<span>o2odev@o2o.kr</span>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -1,21 +1,10 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { useMeQuery } from '@/apis'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
// 협상 유의사항 및 서비스 이용 방법 안내 — 팝업 2종(자동 안내/메뉴 가이드)이 공유하는 본문.
|
||||
// 항목은 회사 설정(companies.settings.guide_notices)에서 오고, 비어 있으면 아래 기본 문구를 쓴다.
|
||||
// VAT/배송비 문구는 채팅 init 메타(useChatInitStore)를 읽어 상품별로 동적 표시한다.
|
||||
const bodyStyle = 'text-sm font-normal leading-relaxed text-neutral-70 break-keep'
|
||||
|
||||
// negodata 회사 설정의 "기본 문구 불러오기" 값과 동일해야 한다
|
||||
// (원본: negodata/front/src/features/settings/catalog.ts DEFAULT_GUIDE_NOTICES).
|
||||
// VAT·배송비 조건은 상품마다 달라 기본 문구에서 뺐다 — 필요한 회사가 항목으로 직접 넣는다.
|
||||
const DEFAULT_NOTICES = [
|
||||
'협상 개시는 협상 참여 버튼을 클릭하는 순간부터 시작됩니다.',
|
||||
'부여된 협상 시간에 응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행될 수 있습니다.',
|
||||
'본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서 얻어진 결과나 내용에 대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를 전제로 진행됩니다.',
|
||||
'협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기 바랍니다.',
|
||||
'안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.',
|
||||
]
|
||||
|
||||
function Bullet({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-start gap-2.5 py-1.5">
|
||||
@@ -26,8 +15,10 @@ function Bullet({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
export function GuideContent() {
|
||||
const { data: user } = useMeQuery()
|
||||
const notices = user?.guideNotices?.length ? user.guideNotices : DEFAULT_NOTICES
|
||||
const { item_vat_yn, item_delivery_fee_yn } = useChatInitStore()
|
||||
// init 미로드/값 없음 → 보수적 기본값 (KT-NEGOWIZ 와 동일한 폴백 규칙)
|
||||
const vat = item_vat_yn || 'VAT별도'
|
||||
const deliveryFee = item_delivery_fee_yn || '배송비별도'
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col">
|
||||
@@ -40,30 +31,59 @@ export function GuideContent() {
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col divide-y divide-border/60 rounded-xl border border-border px-4 py-1">
|
||||
{notices.map((notice) => (
|
||||
<Bullet key={notice}>{notice}</Bullet>
|
||||
))}
|
||||
<Bullet>
|
||||
협상 개시는
|
||||
<span className="font-semibold text-neutral-90">
|
||||
Negosium 시스템의 협상 참여 버튼을 클릭하는 순간부터 시작
|
||||
</span>
|
||||
됩니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>
|
||||
부여된 협상 시간에
|
||||
<span className="font-semibold text-neutral-90">
|
||||
응찰하지 않는 경우, 협상 참여의사가 없는 것으로 간주하여 재견적으로 진행
|
||||
</span>
|
||||
될 수 있습니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>
|
||||
협상에 입력되는 모든 가격은
|
||||
<span className="font-semibold text-negative">
|
||||
{vat} 및 {deliveryFee}
|
||||
</span>
|
||||
기준이며,
|
||||
<span className="font-semibold text-neutral-90">
|
||||
할인을 요청하는 경우 기존 공급가격에 할인율이 적용된 가격으로 환산
|
||||
</span>
|
||||
되어 제시됩니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>
|
||||
본 협상 결과에 대해서는 협상자와 협상대상자 간의 비밀 유지 조건으로 진행되고, 협상에서 얻어진 결과나 내용에
|
||||
대해서는 당사자를 제외하고 제 3자에 공유할 수 없으며, 비밀 유지를 전제로 진행됩니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>
|
||||
협상이 종결되면 특별한 사유 없이 취소 변경이 불가하니, 신중하게 협상에 참여해 주시기 바랍니다.
|
||||
</Bullet>
|
||||
|
||||
<Bullet>안내된 사항 외 부분은 기존 견적 프로세스와 동일한 부분 유의 바랍니다.</Bullet>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 하단 문의 안내 박스 — 연락처는 회사 설정(branding.helpdesk). 미등록이면 박스를 통째로 숨긴다.
|
||||
// 하단 문의 안내 박스
|
||||
export function GuideContactBox() {
|
||||
const { data: user } = useMeQuery()
|
||||
const helpdesk = user?.branding?.helpdesk ?? []
|
||||
if (helpdesk.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col items-center gap-1.5 rounded-xl bg-neutral-10 p-4">
|
||||
<div className={`${bodyStyle} text-center`}>
|
||||
기타 협상 과정에서 궁금하거나 문의하실 사항은 아래 연락처로 상담 부탁드립니다.
|
||||
</div>
|
||||
{helpdesk.map((line) => (
|
||||
<div key={line} className="break-keep text-center text-sm font-bold text-neutral-90">
|
||||
{line}
|
||||
</div>
|
||||
))}
|
||||
<div className="break-keep text-center text-sm font-bold text-neutral-90">
|
||||
헬프데스크 010-0000-0000 · o2odev@o2o.kr
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { X } from 'lucide-react'
|
||||
import { Modal } from '@/components'
|
||||
import { getApiErrorMessage, useRejectMutation } from '@/apis'
|
||||
import { cn, toast } from '@/lib'
|
||||
import { numberToKorean } from '@/features/chat/lib/koreanNumber'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
|
||||
const MAX_PRICE = 999999999999999
|
||||
|
||||
// 사유 목록은 목록 화면의 거부 팝업과 동일하게 맞춘다.
|
||||
const REASONS = ['단종', '품절', '기타'] as const
|
||||
|
||||
// 협상 진행 중 거부 팝업 — 목록의 거부 팝업과 같은 어휘·같은 엔드포인트를 쓰고,
|
||||
// 대화 중이라 이미 오간 가격이 있으므로 공급 희망 가격과 의견을 더 받는다.
|
||||
export function RejectPopup({ onClose }: { onClose: () => void }) {
|
||||
const navigate = useNavigate()
|
||||
const reject = useRejectMutation()
|
||||
const sessionId = useChatStore((s) => s.sessionId)
|
||||
const itemVatYn = useChatInitStore((s) => s.item_vat_yn)
|
||||
const isVAT = itemVatYn === 'VAT별도'
|
||||
|
||||
const [selectedReason, setSelectedReason] = useState<string | null>(null)
|
||||
const [customReason, setCustomReason] = useState('')
|
||||
const [price, setPrice] = useState('')
|
||||
const [opinion, setOpinion] = useState('')
|
||||
const [showError, setShowError] = useState(false)
|
||||
|
||||
const isEtcOpen = selectedReason === '기타'
|
||||
const isPending = reject.isPending
|
||||
const isSubmitDisabled = !selectedReason || (isEtcOpen && !customReason.trim()) || isPending
|
||||
|
||||
const handleReasonClick = (reason: string) => {
|
||||
setShowError(false)
|
||||
if (selectedReason === reason) {
|
||||
setSelectedReason(null)
|
||||
setCustomReason('')
|
||||
} else {
|
||||
setSelectedReason(reason)
|
||||
if (reason !== '기타') setCustomReason('')
|
||||
}
|
||||
}
|
||||
|
||||
const handlePriceChange = (value: string) => {
|
||||
const numeric = value.replace(/\D/g, '')
|
||||
if (numeric && parseInt(numeric) > MAX_PRICE) return
|
||||
setPrice(numeric)
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (isEtcOpen && !customReason.trim()) {
|
||||
setShowError(true)
|
||||
return
|
||||
}
|
||||
if (isSubmitDisabled || !selectedReason) return
|
||||
|
||||
reject.mutate(
|
||||
{
|
||||
sessionId,
|
||||
request: {
|
||||
reject_reason: isEtcOpen ? customReason.trim() : selectedReason,
|
||||
// 선택 입력 — 빈 값이면 보내지 않아 컬럼을 건드리지 않는다.
|
||||
...(price ? { reject_price: parseInt(price) } : {}),
|
||||
...(opinion.trim() ? { opinion: opinion.trim() } : {}),
|
||||
},
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
onClose()
|
||||
toast.warning('협상 거부가 완료되었습니다.')
|
||||
navigate('/list')
|
||||
},
|
||||
onError: (error) => toast.error(getApiErrorMessage(error, '거부 처리에 실패했습니다.')),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const koreanPrice = price && parseInt(price) > 0 ? `[${numberToKorean(parseInt(price))} 원]` : ''
|
||||
|
||||
return (
|
||||
<Modal onClose={onClose}>
|
||||
<div className="flex max-h-[85vh] w-full max-w-md flex-col overflow-hidden rounded-2xl border border-border bg-white shadow-xl animate-scale-in">
|
||||
{/* 헤더 */}
|
||||
<div className="flex shrink-0 items-center justify-between border-b border-border p-5">
|
||||
<h3 className="text-base font-bold text-neutral-90">거부 사유를 입력해주세요</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="닫기"
|
||||
className="flex size-8 items-center justify-center rounded-full text-neutral-60 hover:bg-neutral-10"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 본문 */}
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-5">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{REASONS.map((reason) => (
|
||||
<button
|
||||
key={reason}
|
||||
type="button"
|
||||
onClick={() => handleReasonClick(reason)}
|
||||
disabled={isPending}
|
||||
className={cn(
|
||||
'h-11 rounded-xl border text-sm font-bold transition-all active:scale-[0.98] disabled:opacity-50',
|
||||
selectedReason === reason
|
||||
? 'border-brand-600 bg-brand-light text-brand-600'
|
||||
: 'border-border bg-white text-neutral-70 hover:bg-neutral-10',
|
||||
)}
|
||||
>
|
||||
{reason}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isEtcOpen && (
|
||||
<div className="animate-fade-in">
|
||||
<textarea
|
||||
placeholder="사유를 입력하여 주십시오"
|
||||
value={customReason}
|
||||
onChange={(e) => {
|
||||
setCustomReason(e.target.value)
|
||||
setShowError(false)
|
||||
}}
|
||||
rows={3}
|
||||
disabled={isPending}
|
||||
className={cn(
|
||||
'w-full resize-none rounded-xl border bg-white p-3 text-sm text-neutral-90 outline-none transition-all',
|
||||
'placeholder:text-neutral-50 focus:ring-1',
|
||||
showError
|
||||
? 'border-destructive focus:border-destructive focus:ring-destructive'
|
||||
: 'border-border focus:border-brand-600 focus:ring-brand-600',
|
||||
)}
|
||||
/>
|
||||
{showError && <p className="mt-1.5 text-xs font-medium text-destructive">기타 사유를 입력해주세요</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 공급 희망 가격 (선택) — 결렬 폼과 같은 라벨·표기 */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="text-sm font-bold text-neutral-90">
|
||||
공급 희망 가격 <span className="font-medium text-neutral-60">(선택)</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
className={cn(
|
||||
'h-10 max-w-[200px] rounded-xl border px-3 text-right text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isPending
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
value={price ? parseInt(price).toLocaleString() : ''}
|
||||
onChange={(e) => handlePriceChange(e.target.value)}
|
||||
placeholder="0"
|
||||
disabled={isPending}
|
||||
/>
|
||||
<span className="whitespace-nowrap text-sm text-neutral-70">원{isVAT && '(VAT 별도)'}</span>
|
||||
{koreanPrice && <span className="whitespace-nowrap text-sm text-neutral-50">{koreanPrice}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 의견 (선택) — 결렬 폼과 동일 */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="text-sm font-bold text-neutral-90">
|
||||
의견 <span className="font-medium text-neutral-60">(선택)</span>
|
||||
</div>
|
||||
<textarea
|
||||
value={opinion}
|
||||
onChange={(e) => setOpinion(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={255}
|
||||
disabled={isPending}
|
||||
placeholder="추가로 남길 의견이 있으면 작성해 주세요."
|
||||
className={cn(
|
||||
'w-full resize-none rounded-xl border px-3 py-2 text-sm outline-none transition-all placeholder:text-neutral-50',
|
||||
isPending
|
||||
? 'cursor-not-allowed border-border bg-neutral-10 text-neutral-50'
|
||||
: 'border-border bg-white text-neutral-90 focus:border-brand-600 focus:ring-1 focus:ring-brand-600',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 푸터 — 목록 거부 팝업과 동일 규격 */}
|
||||
<div className="flex shrink-0 gap-2 border-t border-border p-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={isPending}
|
||||
className="h-11 flex-1 rounded-xl border border-border bg-white text-sm font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98] disabled:opacity-50"
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitDisabled}
|
||||
className="h-11 flex-1 rounded-xl bg-brand-600 text-sm font-bold text-white shadow-sm transition-all hover:bg-brand-700 active:scale-[0.98] disabled:opacity-40"
|
||||
>
|
||||
거부 처리
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -24,9 +24,8 @@ const TERMINAL_CODES = new Set<number>([
|
||||
ErrorCode.NEGO_NOT_FOUND,
|
||||
])
|
||||
|
||||
// 진입 로드(init/messages) 시 '잘못된 접근'으로 볼 코드 → 권한 없음 / 없는(또는 남의) 세션 / 진입 불가 상태.
|
||||
// 토스트 안내 후 목록으로 복귀시킨다. (인증≠인가 — 로그아웃하지 않는다)
|
||||
// 종료된 세션(완료·미참여·거부)은 열람 진입이 허용되므로 여기 걸리지 않는다 — 입력만 잠긴다(ChatSection).
|
||||
// 진입 로드(init/messages) 시 '잘못된 접근'으로 볼 코드 → 권한 없음 / 없는(또는 남의) 세션 /
|
||||
// 진입 불가 상태(미참여·거부). 토스트 안내 후 목록으로 복귀시킨다. (인증≠인가 — 로그아웃하지 않는다)
|
||||
const INVALID_ACCESS_CODES = new Set<number>([
|
||||
ErrorCode.NEGO_FORBIDDEN,
|
||||
ErrorCode.NEGO_NOT_FOUND,
|
||||
@@ -116,8 +115,8 @@ export function useChatController(sessionId: string) {
|
||||
if (data.message) s.appendMessage(mapMessage(data.message))
|
||||
s.setIsLoading(false)
|
||||
// 협상 종료 전이(완료/거부 등): 목록 캐시만 무효화해 /list 복귀 시 최신 상태를 보장한다.
|
||||
// init 은 '진입 메타'라 화면에서 재조회하지 않는다 — 방금 종료한 화면의 입력이 열람 모드로
|
||||
// 갈아치워지지 않게 한다. 재진입 시 최신 status 는 언마운트의 removeQueries 가 보장한다.
|
||||
// init 은 '진입 메타'라 화면에서 재조회하지 않는다 — 재조회하면 미참여/거부 진입 게이트(1301)에
|
||||
// 걸려 방금 정상 종료한 사용자가 튕겨난다. 재진입 시 최신 status 는 언마운트의 removeQueries 가 보장한다.
|
||||
if (data.session_status !== SessionStatus.IN_PROGRESS || data.message?.chat_end) {
|
||||
queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() })
|
||||
}
|
||||
|
||||
@@ -2,17 +2,6 @@ import type { ChatMessage, UserButtonConfig } from '@/features/chat/types'
|
||||
|
||||
export const GO_TO_LIST_TEXT = '상품 목록으로 가기'
|
||||
|
||||
// 협상 거부 진입점을 숨기는 액션바 상태.
|
||||
// reject=봇이 이미 결렬을 선언(그 폼이 최종가를 받는다) / extra-info=타결 후 동의 단계 / loading=응답 대기.
|
||||
const NO_REJECT_TYPES = ['', 'loading', 'reject', 'extra-info']
|
||||
|
||||
// 채팅 안에서 협상을 거부할 수 있는 상태인지 — 대화가 끝나지 않고 협력사 입력을 기다리는 동안만.
|
||||
export function canRejectNegotiation(messages: ChatMessage[], config: UserButtonConfig): boolean {
|
||||
if (!messages || messages.length === 0) return false
|
||||
if (messages[messages.length - 1].chat_end) return false
|
||||
return !NO_REJECT_TYPES.includes(config.type)
|
||||
}
|
||||
|
||||
// 마지막 봇 메시지의 next_input_mode 로 하단 입력 UI 구성을 결정한다.
|
||||
export function deriveUserButtonConfig(
|
||||
messages: ChatMessage[],
|
||||
|
||||
@@ -29,7 +29,7 @@ export function GuidePopup({ onClose }: { onClose: () => void }) {
|
||||
<Row badge="협상 중" tone="prog" text="가격을 조율하는 중입니다. 이어서 진행하세요." />
|
||||
<Row badge="협상 완료" tone="done" text="가격 제출을 마쳤습니다. 최종 결과는 견적 마감 후 아래 '결과'로 표시됩니다." />
|
||||
<Row badge="협상 미참여" tone="none" text="기한 내 참여하지 않아 종료된 건입니다." />
|
||||
<Row badge="협상 거부" tone="reject" text="내가 거부한 건입니다." />
|
||||
<Row badge="협상 거절" tone="reject" text="내가 참여를 거절한 건입니다." />
|
||||
</Section>
|
||||
|
||||
<Section title="협상 결과" desc="견적이 마감된 뒤 정해지는 낙찰 결과입니다. 마감 전에는 표시되지 않습니다.">
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Loader2, MessageSquareText } from 'lucide-react'
|
||||
import { cn, formatKstDateTime } from '@/lib'
|
||||
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
|
||||
import type { ListItem } from '@/features/list/types'
|
||||
import { statusMeta, canEnterChat, isEndedStatus, RESULT_META } from '@/features/list/lib/status'
|
||||
import { statusMeta, RESULT_META } from '@/features/list/lib/status'
|
||||
|
||||
interface WorkspaceCardsProps {
|
||||
items: ListItem[]
|
||||
@@ -55,11 +55,10 @@ function Card({
|
||||
onMemo: (item: ListItem) => void
|
||||
}) {
|
||||
const meta = statusMeta(item.session_status)
|
||||
const ended = isEndedStatus(item.session_status)
|
||||
const canEnter = canEnterChat(item.session_status, item.hasChat)
|
||||
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
|
||||
const canReject = ['협상생성', '협상중'].includes(item.session_status)
|
||||
const isDone = item.session_status === '협상완료'
|
||||
const enterLabel = ended ? '결과 보기' : '협상 입장'
|
||||
const enterLabel = isDone ? '결과 보기' : '협상 입장'
|
||||
// 재협상: 요청 가능하면 버튼, 이미 요청했으면 진행 상태를 보여준다.
|
||||
const renegoLabel = RENEGO_STATUS_LABEL[item.renegotiationStatus] ?? ''
|
||||
|
||||
@@ -139,7 +138,7 @@ function Card({
|
||||
onClick={() => onReject(item)}
|
||||
className="flex-1 rounded-lg border border-border py-2 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
|
||||
>
|
||||
협상 거부
|
||||
거절
|
||||
</button>
|
||||
)}
|
||||
{canEnter && (
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Loader2, MessageSquareText } from 'lucide-react'
|
||||
import { cn, formatKstDateTime } from '@/lib'
|
||||
import { RENEGO_STATUS_LABEL } from '@/apis/negotiation/negotiation.type'
|
||||
import type { ListItem } from '@/features/list/types'
|
||||
import { statusMeta, canEnterChat, isEndedStatus, RESULT_META } from '@/features/list/lib/status'
|
||||
import { statusMeta, RESULT_META } from '@/features/list/lib/status'
|
||||
|
||||
interface WorkspaceTableProps {
|
||||
items: ListItem[]
|
||||
@@ -73,11 +73,10 @@ function Row({
|
||||
onMemo: (item: ListItem) => void
|
||||
}) {
|
||||
const meta = statusMeta(item.session_status)
|
||||
const ended = isEndedStatus(item.session_status)
|
||||
const canEnter = canEnterChat(item.session_status, item.hasChat)
|
||||
const canEnter = !['미참여', '협상거부'].includes(item.session_status)
|
||||
const canReject = ['협상생성', '협상중'].includes(item.session_status)
|
||||
const isDone = item.session_status === '협상완료'
|
||||
const enterLabel = ended ? '결과 보기' : '협상 입장'
|
||||
const enterLabel = isDone ? '결과 보기' : '협상 입장'
|
||||
|
||||
return (
|
||||
<tr className="border-b border-border/60 transition-colors last:border-0 hover:bg-table-hover/70">
|
||||
@@ -151,7 +150,7 @@ function Row({
|
||||
onClick={() => onReject(item)}
|
||||
className="rounded-lg border border-border px-3 py-1.5 text-xs font-bold text-neutral-70 transition-all hover:bg-neutral-10 active:scale-[0.98]"
|
||||
>
|
||||
협상 거부
|
||||
거절
|
||||
</button>
|
||||
)}
|
||||
{canEnter ? (
|
||||
|
||||
@@ -24,7 +24,6 @@ import { ExtraInfoPopup } from '@/features/list/components/ExtraInfoPopup'
|
||||
import { RenegotiationPopup } from '@/features/list/components/RenegotiationPopup'
|
||||
import { RenegotiationMemoPopup } from '@/features/list/components/RenegotiationMemoPopup'
|
||||
import { GuidePopup } from '@/features/list/components/GuidePopup'
|
||||
import { isEndedStatus } from '@/features/list/lib/status'
|
||||
import type { ListItem } from '@/features/list/types'
|
||||
|
||||
// 상태별 거부 불가 안내
|
||||
@@ -71,11 +70,6 @@ export function ListWorkspace() {
|
||||
const [guideOpen, setGuideOpen] = useState(false)
|
||||
|
||||
const handleEnter = (item: ListItem) => {
|
||||
// 종료 건(완료·미참여·거부)은 열람 전용 — 참여 API 는 미참여/거부를 막으므로 바로 채팅으로 보낸다.
|
||||
if (isEndedStatus(item.session_status)) {
|
||||
navigate(`/chat?session_id=${item.session_id}`)
|
||||
return
|
||||
}
|
||||
setEnteringId(item.session_id)
|
||||
participate.mutate(item.session_id, {
|
||||
onSuccess: () => navigate(`/chat?session_id=${item.session_id}`),
|
||||
@@ -100,8 +94,8 @@ export function ListWorkspace() {
|
||||
reject.mutate(
|
||||
{ sessionId: rejectTarget.session_id, request: { reject_reason: reason } },
|
||||
{
|
||||
onSuccess: () => toast.warning('협상 거부가 완료되었습니다.'),
|
||||
onError: (error) => toast.error(getApiErrorMessage(error, '거부 처리에 실패했습니다.')),
|
||||
onSuccess: () => toast.warning('참여 거절이 완료되었습니다.'),
|
||||
onError: (error) => toast.error(getApiErrorMessage(error, '거절 처리에 실패했습니다.')),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -42,6 +42,5 @@ export function toListItem(api: SessionListItem): ListItem {
|
||||
renegotiationStatus: api.renegotiation_status ?? 0,
|
||||
renegotiationMemo: api.renegotiation_memo ?? '',
|
||||
result: api.result ?? 0,
|
||||
hasChat: api.has_chat ?? false,
|
||||
}
|
||||
}
|
||||
@@ -11,25 +11,13 @@ export const STATUS_META: Record<string, StatusMeta> = {
|
||||
협상중: { display: '협상 중', badge: 'bg-[#FFF3E5] text-[#F5A623]', dot: 'bg-[#F5A623]' },
|
||||
협상완료: { display: '협상 완료', badge: 'bg-[#EAFDF3] text-success', dot: 'bg-success' },
|
||||
미참여: { display: '협상 미참여', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' },
|
||||
협상거부: { display: '협상 거부', badge: 'bg-[#FFEBEB] text-[#FF4D4F]', dot: 'bg-[#FF4D4F]' },
|
||||
협상거부: { display: '협상 거절', badge: 'bg-[#FFEBEB] text-[#FF4D4F]', dot: 'bg-[#FF4D4F]' },
|
||||
}
|
||||
|
||||
export function statusMeta(label: string): StatusMeta {
|
||||
return STATUS_META[label] ?? { display: label || '-', badge: 'bg-neutral-20 text-neutral-60', dot: 'bg-neutral-60' }
|
||||
}
|
||||
|
||||
// 종료 상태 — 대화를 이어갈 수 없고 지난 이력만 '결과 보기'로 열람한다(백엔드 send 도 협상중만 허용).
|
||||
const ENDED_STATUSES = ['협상완료', '미참여', '협상거부']
|
||||
|
||||
export function isEndedStatus(label: string): boolean {
|
||||
return ENDED_STATUSES.includes(label)
|
||||
}
|
||||
|
||||
// 채팅 진입 가능 여부. 진행 건은 항상, 종료 건은 볼 대화가 있을 때만 — 초청만 받고 끝난 건은 열어도 빈 화면이다.
|
||||
export function canEnterChat(label: string, hasChat: boolean): boolean {
|
||||
return !isEndedStatus(label) || hasChat
|
||||
}
|
||||
|
||||
// 협상 결과(SessionResult 코드) → 완료 건에 붙는 결과 배지. 0(미정)은 표시하지 않는다.
|
||||
// 결렬(3)은 재협상 요청 대상이라 눈에 띄게 노랑으로 둔다.
|
||||
export const RESULT_META: Record<number, { label: string; badge: string }> = {
|
||||
|
||||
@@ -13,5 +13,4 @@ export type ListItem = {
|
||||
renegotiationStatus: number // 0=없음 1=심사중 2=승인 3=반려 4=철회
|
||||
renegotiationMemo: string // 담당자 심사 메모(반려 사유)
|
||||
result: number // 협상 결과: 0=미정 1=낙찰 2=미낙찰 3=결렬(개찰)
|
||||
hasChat: boolean // 대화 이력 존재 — 종료된 협상의 '결과 보기' 노출 조건
|
||||
}
|
||||
@@ -44,7 +44,7 @@ export function MainLayout({
|
||||
header,
|
||||
children,
|
||||
}: MainLayoutProps) {
|
||||
const { data: user } = useMeQuery() // 회사 브랜딩(서비스명/로고) 주입 — 색은 솔루션 고정
|
||||
const { data: user } = useMeQuery() // 회사 브랜딩(서비스명/로고) 주입
|
||||
const panes = (
|
||||
<>
|
||||
<aside className={cn(styles.sidebar, SIDEBAR_WIDTH[sidebarWidth])}>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Logo } from '@/components'
|
||||
import { LoginForm, usePreLoginBranding } from '@/features/auth'
|
||||
|
||||
export function LoginPage() {
|
||||
// 초청 링크의 session_id(없으면 직전 로그인 캐시)로 회사 브랜딩(서비스명·로고)을 먼저 그린다.
|
||||
// 초청 링크의 session_id(없으면 직전 로그인 캐시)로 회사 브랜딩을 먼저 그린다.
|
||||
const branding = usePreLoginBranding()
|
||||
|
||||
// 이미 로그인된 상태면 목록으로
|
||||
@@ -31,13 +31,11 @@ export function LoginPage() {
|
||||
<LoginForm />
|
||||
</div>
|
||||
|
||||
{/* 푸터 — 문의처(회사 설정 branding.helpdesk, 미등록이면 생략) + 솔루션/제작사 표기(고정) */}
|
||||
{/* 푸터 — 문의처 + 솔루션/제작사 표기(회사 브랜딩과 무관하게 고정) */}
|
||||
<div className="flex flex-col items-center gap-1">
|
||||
{(branding?.helpdesk ?? []).map((line) => (
|
||||
<p key={line} className="text-xs font-medium text-neutral-60">
|
||||
문의: {line}
|
||||
</p>
|
||||
))}
|
||||
<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>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
node_modules
|
||||
build
|
||||
.react-router
|
||||
.vercel
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { VercelRequest, VercelResponse } from "@vercel/node"
|
||||
|
||||
/*
|
||||
* 리드 수집 엔드포인트 (Vercel 서버리스 함수).
|
||||
*
|
||||
* 랜딩은 ssr:false 정적 빌드라 서버 라우트가 없다. 그래서 /api 디렉터리의 함수로 받는다.
|
||||
* 클라이언트는 같은 오리진으로 쏘므로 엔드포인트 환경변수도, CORS 설정도 필요 없다.
|
||||
*
|
||||
* ── 리드를 잃지 않는 것이 이 파일의 유일한 책임이다 ──────────────────────────
|
||||
* 기존 문의 폼은 1.2초 뒤 성공 화면만 띄우고 아무 데도 보내지 않았다. 화면은
|
||||
* "접수되었습니다"인데 영업이 받을 리드는 없고, 아무도 그 사실을 몰랐다.
|
||||
*
|
||||
* 그래서 순서를 이렇게 잡는다.
|
||||
* 1) 먼저 구조화된 로그를 남긴다. 웹훅이 죽어도 Vercel 로그에 리드가 남는다.
|
||||
* 2) LEAD_WEBHOOK_URL 이 있으면 그리로 전달한다(Slack Incoming Webhook·Zapier·자체 API 모두 POST 를 받는다).
|
||||
* 3) 웹훅 전달이 실패해도 200 을 준다 — 1) 에서 이미 리드를 확보했으므로 방문자에게
|
||||
* 다시 입력하라고 할 이유가 없다. 대신 실패는 로그에 크게 남긴다.
|
||||
*
|
||||
* 로그는 CRM 이 아니라 최후의 그물이다. LEAD_WEBHOOK_URL 은 반드시 설정해야 한다.
|
||||
*/
|
||||
|
||||
const MAX_FIELD = 500
|
||||
|
||||
type LeadBody = {
|
||||
source?: string
|
||||
name?: string
|
||||
email?: string
|
||||
company?: string
|
||||
phone?: string
|
||||
message?: string
|
||||
/* 봇 함정. 사람 눈에 안 보이는 필드라 값이 차 있으면 자동 제출이다. */
|
||||
website?: string
|
||||
}
|
||||
|
||||
const clean = (v: unknown) => (typeof v === "string" ? v.trim().slice(0, MAX_FIELD) : "")
|
||||
|
||||
/** 느슨한 검사. 정규식으로 이메일을 엄밀히 검증하려는 시도는 늘 진짜 주소를 막는다. */
|
||||
const emailLike = (v: string) => v.length >= 5 && v.includes("@") && !v.startsWith("@") && !v.endsWith("@") && !/\s/.test(v)
|
||||
|
||||
export default async function handler(req: VercelRequest, res: VercelResponse) {
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "POST")
|
||||
return res.status(405).json({ ok: false, error: "method_not_allowed" })
|
||||
}
|
||||
|
||||
const body = (typeof req.body === "string" ? safeParse(req.body) : req.body) as LeadBody | null
|
||||
if (!body) return res.status(400).json({ ok: false, error: "invalid_json" })
|
||||
|
||||
// 봇은 조용히 돌려보낸다. 400 을 주면 어떤 필드가 함정인지 알려주는 셈이다.
|
||||
if (clean(body.website)) return res.status(200).json({ ok: true })
|
||||
|
||||
const lead = {
|
||||
source: clean(body.source) || "unknown",
|
||||
name: clean(body.name),
|
||||
email: clean(body.email),
|
||||
company: clean(body.company),
|
||||
phone: clean(body.phone),
|
||||
message: clean(body.message),
|
||||
submittedAt: new Date().toISOString(),
|
||||
userAgent: clean(req.headers["user-agent"]),
|
||||
}
|
||||
|
||||
if (!lead.name || !emailLike(lead.email)) {
|
||||
return res.status(400).json({ ok: false, error: "invalid_input" })
|
||||
}
|
||||
|
||||
// 1) 무슨 일이 있어도 먼저 남긴다.
|
||||
console.log("[lead]", JSON.stringify(lead))
|
||||
|
||||
// 2) 사람이 실제로 보는 곳으로 전달.
|
||||
const webhook = process.env.LEAD_WEBHOOK_URL
|
||||
if (!webhook) {
|
||||
console.warn("[lead] LEAD_WEBHOOK_URL 미설정 — 리드가 로그에만 남습니다. 웹훅을 설정하세요.")
|
||||
return res.status(200).json({ ok: true, delivered: false })
|
||||
}
|
||||
|
||||
try {
|
||||
const upstream = await fetch(webhook, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
// Slack Incoming Webhook 은 text 를 읽고, 나머지 수신처는 보통 원본 필드를 읽는다.
|
||||
// 둘 다 담아 보내면 수신처를 바꿀 때 이 파일을 고칠 일이 없다.
|
||||
body: JSON.stringify({ text: summarize(lead), ...lead }),
|
||||
})
|
||||
if (!upstream.ok) {
|
||||
console.error("[lead] 웹훅 전달 실패", upstream.status, JSON.stringify(lead))
|
||||
return res.status(200).json({ ok: true, delivered: false })
|
||||
}
|
||||
return res.status(200).json({ ok: true, delivered: true })
|
||||
} catch (e) {
|
||||
console.error("[lead] 웹훅 예외", e, JSON.stringify(lead))
|
||||
return res.status(200).json({ ok: true, delivered: false })
|
||||
}
|
||||
}
|
||||
|
||||
function safeParse(s: string) {
|
||||
try {
|
||||
return JSON.parse(s)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function summarize(l: { source: string; name: string; email: string; company: string; phone: string; message: string }) {
|
||||
const rows = [
|
||||
`*새 리드* (${l.source})`,
|
||||
`이름: ${l.name}`,
|
||||
`이메일: ${l.email}`,
|
||||
l.company && `회사: ${l.company}`,
|
||||
l.phone && `연락처: ${l.phone}`,
|
||||
l.message && `내용: ${l.message}`,
|
||||
].filter(Boolean)
|
||||
return rows.join("\n")
|
||||
}
|
||||
+90
-16
@@ -10,38 +10,112 @@
|
||||
src: url('/fonts/PretendardVariable.woff2') format('woff2');
|
||||
}
|
||||
|
||||
/* 영문 디스플레이 서체 — 이탤릭 가변(400~900), latin 서브셋.
|
||||
INFINITH 디자인 시스템과 같은 Playfair Display 를 쓴다. */
|
||||
@font-face {
|
||||
font-family: 'Playfair Display';
|
||||
font-style: italic;
|
||||
font-weight: 400 900;
|
||||
font-display: swap;
|
||||
src: url('/fonts/PlayfairDisplay-Italic.woff2') format('woff2');
|
||||
}
|
||||
|
||||
/*
|
||||
* 랜딩 디자인 토큰 (Toss 스타일 라이트 팔레트).
|
||||
* 랜딩 디자인 토큰.
|
||||
* 색은 전부 여기서만 정의하고, 컴포넌트는 토큰 클래스(text-ink, bg-primary …)만 쓴다.
|
||||
*
|
||||
* 구조는 두 겹이다.
|
||||
* - 다크 무대(stage) : 히어로·협상 데모. 협상이 벌어지는 순간에만 조명을 끈다.
|
||||
* - 라이트 본문 : 나머지 섹션. 광고 유입 전환율을 위해 밝게 유지.
|
||||
*/
|
||||
@theme {
|
||||
--font-sans: 'Pretendard Variable', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif;
|
||||
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
|
||||
/* 영문 디스플레이 — 라벨·강조 전용. 한글 본문은 절대 이걸로 쓰지 않는다
|
||||
(Playfair 는 한글 글리프가 없어 Pretendard 로 폴백되며 톤이 깨진다). */
|
||||
--font-display: 'Playfair Display', 'Pretendard Variable', Georgia, serif;
|
||||
|
||||
/* 브랜드 */
|
||||
--color-primary: #476EFF;
|
||||
--color-primary-deep: #2F52E0; /* hover */
|
||||
--color-primary-soft: #ECF0FF; /* 연한 파랑 배경 — 봇 말풍선, 배지 */
|
||||
/* ── 브랜드 액센트 ──────────────────────────────────────────────
|
||||
여기 3줄이 브랜드 색상각의 단일 소스다. 딥틸(#005961 / #00434A / #E3F4F5)로
|
||||
되돌리려면 이 3줄만 갈아끼우면 되고, 나머지 토큰·컴포넌트는 손대지 않는다. */
|
||||
--color-primary: #0101F3; /* 일렉트릭 블루 — 라이트 배경 전용. 레퍼런스 실측값 */
|
||||
/* 다크 무대용 액센트. #0101F3 을 #070E24 위에 얹으면 명암비가 2.0:1 로,
|
||||
WCAG 최소(4.5:1)의 절반도 안 된다 — 둘 다 어두운 색이라 그렇다.
|
||||
아래 값은 무대 배경 대비 약 6:1 이다. 무대 위 파란 글자는 반드시 이걸 쓴다. */
|
||||
--color-primary-on-stage: #7C8CFF;
|
||||
--color-primary-deep: #0101C4; /* hover */
|
||||
--color-primary-soft: #EAEAFF; /* 연한 배경 — 에이전트 말풍선, 배지 */
|
||||
|
||||
/* 텍스트. ink 는 다크 섹션에선 배경색으로도 쓴다 */
|
||||
--color-ink: #191F28;
|
||||
--color-ink-soft: #4E5968; /* 보조 본문 */
|
||||
--color-ink-muted: #8B95A1; /* 캡션 */
|
||||
--color-ink-faint: #B0B8C1; /* 플레이스홀더·각주 */
|
||||
/* ── 상대편(공급사) ────────────────────────────────────────────
|
||||
협상은 두 주체가 매 턴 구분돼야 읽힌다. 민트는 블루와 색상각 70° 차이라
|
||||
구분되면서도 같은 한색 계열이라 화면이 따로 놀지 않는다.
|
||||
NEGO WIZ 로고 민트(#0FFFD6)에서 왔다. */
|
||||
--color-counter: #0FFFD6; /* 무대 위 상대측 텍스트·강조 */
|
||||
--color-counter-deep: #077A66; /* 라이트 배경 위 텍스트 (흰 바탕 대비 확보용) */
|
||||
--color-counter-surface: #0A2F35; /* 무대 위 상대측 말풍선 바닥 */
|
||||
|
||||
/* ── 다크 무대 ────────────────────────────────────────────────── */
|
||||
--color-stage: #070E24; /* 무대 바닥 (그라데이션의 중간값) */
|
||||
--color-stage-deep: #03060F; /* 무대 가장자리 — 어두워지며 공간이 뒤로 물러난다 */
|
||||
--color-stage-lift: #16205A; /* 무대 상단 광원 — 여기서 빛이 온다 */
|
||||
--color-stage-raised: #101A3D; /* 무대 위 카드·상대측 말풍선 */
|
||||
--color-stage-line: #1E2A52; /* 무대 위 테두리 */
|
||||
--color-on-stage: #FFFFFF; /* 무대 위 1차 텍스트 */
|
||||
/* 2·3차 텍스트는 중립 회색 대신 연보라 계열로 둔다. 네이비 위에 색상각이 다른
|
||||
회색을 얹으면 탁해지는데, 같은 한색 가족이면 밝게 올려도 화면이 정돈된다.
|
||||
#F5F3FF 는 ADO2 디자인 시스템의 연보라 패널 색이다. */
|
||||
--color-on-stage-soft: #F5F3FF; /* 무대 위 2차 텍스트 — 2톤 헤드라인의 약한 쪽 */
|
||||
--color-on-stage-muted: #C6C0E4; /* 무대 위 라벨·캡션 */
|
||||
|
||||
/* ── 라이트 본문 텍스트 ────────────────────────────────────────
|
||||
먹색에 브랜드 색조를 섞어둔다. 순수 회색이면 페이지가 따로 논다. */
|
||||
--color-ink: #0B1024;
|
||||
--color-ink-soft: #454E6B; /* 보조 본문 */
|
||||
--color-ink-muted: #838CAA; /* 캡션 */
|
||||
--color-ink-faint: #AAB1C7; /* 플레이스홀더·각주 */
|
||||
|
||||
/* 면·선 */
|
||||
--color-surface: #F9FAFB; /* 회색 섹션 배경 */
|
||||
--color-surface-neu: #F2F4F7; /* 뉴모피즘 히어로 전용 배경 */
|
||||
--color-fill: #F2F4F6; /* 회색 채움 — 탭 트랙, 보조 버튼 */
|
||||
--color-fill-hover: #EAECEF;
|
||||
--color-line: #F2F4F6; /* 섹션 구분선 */
|
||||
--color-line-strong: #E5E8EB; /* 카드 테두리 */
|
||||
--color-surface: #F7F8FC; /* 회색 섹션 배경 */
|
||||
--color-surface-neu: #F1F3F9; /* 보조 섹션 배경 */
|
||||
--color-fill: #F0F2F8; /* 회색 채움 — 탭 트랙, 보조 버튼 */
|
||||
--color-fill-hover: #E6E9F2;
|
||||
--color-line: #EEF0F6; /* 섹션 구분선 */
|
||||
--color-line-strong: #E0E4EE; /* 카드 테두리 */
|
||||
|
||||
--color-positive: #0B8F57; /* 낙찰·성공 강조 */
|
||||
--color-positive-soft: #E8F7EF; /* 연한 초록 배경 — 낙찰 배지 */
|
||||
|
||||
--color-accent: #8F52FF; /* 보라 강조 — 결과 탭·히어로 장식 */
|
||||
--color-accent-soft: #F4EFFF; /* 연한 보라 배경 */
|
||||
|
||||
/* ── 모서리 ────────────────────────────────────────────────────
|
||||
레퍼런스 실측은 3.5~7px 이다. 20~32px 짜리 뭉툭한 카드가 제네릭 SaaS 의
|
||||
가장 강한 신호라, 여기서는 세 값으로만 고정한다.
|
||||
card — 카드·패널·목업
|
||||
control — 탭·배지·입력 등 작은 요소
|
||||
full — 버튼·아바타 (Tailwind 기본 rounded-full 사용) */
|
||||
--radius-card: 8px;
|
||||
--radius-control: 4px;
|
||||
}
|
||||
|
||||
/* 다크 무대 배경 그라데이션.
|
||||
단색 배경은 아무리 입자에 원근을 줘도 평면으로 읽힌다. 위쪽에 광원을 두고
|
||||
가장자리로 갈수록 어두워지게 하면 화면 자체에 안팎이 생겨 깊이가 성립한다. */
|
||||
.stage-bg {
|
||||
background:
|
||||
radial-gradient(120% 78% at 50% 8%, var(--color-stage-lift) 0%, transparent 62%),
|
||||
radial-gradient(100% 100% at 50% 42%, var(--color-stage) 0%, var(--color-stage-deep) 100%);
|
||||
}
|
||||
|
||||
/* 드래그 선택 색.
|
||||
루트에 걸린 selection:text-primary 는 라이트 본문 기준이다. 그 값(#0101F3)을 다크 무대
|
||||
위에 얹으면 명암비가 2.0:1 이라 — 위 --color-primary-on-stage 주석이 경고하는 바로 그
|
||||
상황 — 무대 섹션에서 텍스트를 드래그하면 글자가 사라진다.
|
||||
무대 안에서는 무대용 액센트로 갈아끼운다. 라이트 본문은 기존 그대로. */
|
||||
.stage-bg ::selection,
|
||||
[data-stage-hero] ::selection {
|
||||
background-color: color-mix(in srgb, var(--color-primary-on-stage) 30%, transparent);
|
||||
color: var(--color-on-stage);
|
||||
}
|
||||
|
||||
html {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Bot, Clock, Database, Handshake, Scale, TrendingUp, UserRound, type LucideIcon } from "lucide-react"
|
||||
import { Clock, Database, Handshake, Scale, TrendingUp, UserRound, type LucideIcon } from "lucide-react"
|
||||
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { CONTROL_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { useFadeUp } from "@/lib/motion"
|
||||
|
||||
@@ -44,28 +44,31 @@ export function Comparison() {
|
||||
|
||||
return (
|
||||
<Section id="comparison">
|
||||
<motion.div {...fadeUp} className="mb-12">
|
||||
<motion.div {...fadeUp}>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
eyebrow="WHY NEGOTIUM"
|
||||
eyebrow="Before & After"
|
||||
title="협상 방식을 바꾸면, 무엇이 달라질까요"
|
||||
description="기존 가격 협상의 문제는 사람이 아니라 구조입니다."
|
||||
descriptionClassName="mt-4 text-[17px] max-w-2xl"
|
||||
descriptionClassName="max-w-2xl"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
{/* 모드 토글 — 이용 가이드 탭과 같은 세그먼트 문법 */}
|
||||
<motion.div {...toggleFadeUp} className="flex justify-center mb-14">
|
||||
<div className="p-1 bg-fill rounded-[14px] inline-flex gap-1">
|
||||
{/* 모드 토글 — 이용 가이드 탭과 같은 세그먼트 문법.
|
||||
아래 간격(CONTROL_GAP)은 머리 간격보다 좁다. 토글은 자기가 조종하는
|
||||
카드들과 한 덩어리로 읽혀야지, 제목에 붙으면 무엇을 바꾸는 스위치인지 흐려진다. */}
|
||||
<motion.div {...toggleFadeUp} className={`flex justify-center ${CONTROL_GAP}`}>
|
||||
{/* 액티브를 bg-white 로 두면 트랙(bg-fill #F0F2F8) 과 거의 같은 밝기라
|
||||
멀리서 어느 쪽이 켜졌는지 안 보인다. 채움색으로 확실히 갈라준다. */}
|
||||
<div className="p-1.5 bg-fill rounded-full inline-flex gap-1.5">
|
||||
{MODES.map((m) => (
|
||||
<button
|
||||
key={m.key}
|
||||
onClick={() => selectMode(m.key)}
|
||||
className={`px-5 py-2.5 rounded-[10px] text-xs sm:text-sm font-bold transition-all flex items-center gap-2 cursor-pointer ${
|
||||
mode === m.key ? "bg-white text-primary shadow-sm" : "text-ink-soft hover:text-ink"
|
||||
className={`px-7 py-3 rounded-full text-[15px] font-semibold transition-colors cursor-pointer ${
|
||||
mode === m.key ? "bg-primary text-white" : "text-ink-muted hover:text-ink"
|
||||
}`}
|
||||
>
|
||||
{m.key === "after" && <Bot className="w-4 h-4" />}
|
||||
<span>{m.label}</span>
|
||||
</button>
|
||||
))}
|
||||
@@ -85,7 +88,7 @@ type Mode = "before" | "after"
|
||||
|
||||
const MODES: { key: Mode; label: string }[] = [
|
||||
{ key: "before", label: "기존 방식" },
|
||||
{ key: "after", label: "negotium 도입 후" },
|
||||
{ key: "after", label: "네고시움 도입 후" },
|
||||
]
|
||||
|
||||
type CompareItem = { label: string; icon: LucideIcon; before: string; after: string }
|
||||
@@ -97,13 +100,13 @@ function CompareCard({ item, mode, index }: { item: CompareItem; mode: Mode; ind
|
||||
return (
|
||||
<motion.div
|
||||
{...fadeUp}
|
||||
className={`p-7 rounded-[28px] flex flex-col gap-5 transition-colors duration-500 ${
|
||||
className={`p-7 rounded-card flex flex-col gap-5 transition-colors duration-500 ${
|
||||
active ? "bg-primary-soft/60" : "bg-surface"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div
|
||||
className={`w-11 h-11 rounded-2xl flex items-center justify-center transition-colors duration-500 ${
|
||||
className={`w-11 h-11 rounded-card flex items-center justify-center transition-colors duration-500 ${
|
||||
active ? "bg-primary/10 text-primary" : "bg-ink-muted/10 text-ink-muted"
|
||||
}`}
|
||||
>
|
||||
@@ -156,14 +159,14 @@ const ITEMS: CompareItem[] = [
|
||||
{
|
||||
label: "사람",
|
||||
icon: UserRound,
|
||||
before: "반복 흥정과 감정 노동에 지쳐 고급 인력이 이탈합니다.",
|
||||
after: "감정 소모는 봇이 맡고, 사람은 전략 업무와 대형 거래에 집중합니다.",
|
||||
before: "반복 협상에 시간을 뺏겨 전략 업무가 계속 밀립니다.",
|
||||
after: "반복 협상은 에이전트가 맡고, 담당자는 전략 구매와 대형 건에 집중합니다.",
|
||||
},
|
||||
{
|
||||
label: "파트너 관계",
|
||||
icon: Handshake,
|
||||
before: "감정 과열과 실랑이로 장기 파트너십이 흔들립니다.",
|
||||
after: "악역은 봇이 — 압박 없는 상시 협상으로 관계가 개선됩니다.",
|
||||
before: "담당자마다 기준이 달라 협력사가 조건을 예측하기 어렵습니다.",
|
||||
after: "에이전트가 같은 기준으로 상시 응대해 조건이 일관됩니다.",
|
||||
},
|
||||
{
|
||||
label: "의사 결정",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Building, CheckCircle2, Loader2, Mail, Phone, Send } from "lucide-react"
|
||||
import { Check, Loader2 } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input, Textarea } from "@/components/ui/input"
|
||||
@@ -8,7 +8,7 @@ import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import type { LucideIcon } from "lucide-react"
|
||||
import { submitLead } from "@/lib/lead"
|
||||
|
||||
const EMPTY_FORM = {
|
||||
companyName: '',
|
||||
@@ -18,19 +18,33 @@ const EMPTY_FORM = {
|
||||
message: '',
|
||||
}
|
||||
|
||||
/** 도입 문의 폼. 백엔드 미연결 — 제출은 데모 처리(1.2초 후 성공 화면). */
|
||||
/*
|
||||
* 상담 신청 폼 — 고관여 경로. 저관여 리드 캡처는 데모 요청 모달이 맡는다.
|
||||
*
|
||||
* 예전에는 백엔드가 없어서 1.2초 뒤 성공 화면만 띄웠다. 화면은 "접수되었습니다"인데
|
||||
* 영업이 받을 리드는 존재하지 않았고, 아무도 그 사실을 몰랐다. 지금은 데모 요청과
|
||||
* 같은 서버리스 함수(api/lead.ts)로 보내고, 서버가 리드를 확보했을 때만 성공을 띄운다.
|
||||
*/
|
||||
export function Contact() {
|
||||
const [formData, setFormData] = useState(EMPTY_FORM)
|
||||
const [status, setStatus] = useState<'idle' | 'submitting' | 'success'>('idle')
|
||||
const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle')
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!formData.companyName || !formData.contactName || !formData.email || !formData.phone) {
|
||||
return
|
||||
}
|
||||
|
||||
setStatus('submitting')
|
||||
setTimeout(() => setStatus('success'), 1200)
|
||||
const result = await submitLead({
|
||||
source: 'contact',
|
||||
name: formData.contactName,
|
||||
email: formData.email,
|
||||
company: formData.companyName,
|
||||
phone: formData.phone,
|
||||
message: formData.message,
|
||||
})
|
||||
setStatus(result.ok ? 'success' : 'error')
|
||||
}
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
@@ -41,22 +55,12 @@ export function Contact() {
|
||||
const submitting = status === 'submitting'
|
||||
|
||||
return (
|
||||
<Section
|
||||
id="contact-section"
|
||||
bordered
|
||||
decor={
|
||||
<>
|
||||
<div className="absolute top-[20%] right-[10%] w-72 h-72 bg-primary/5 blur-[100px] rounded-full pointer-events-none" />
|
||||
<div className="absolute bottom-[10%] left-[5%] w-96 h-96 bg-primary/3 blur-[120px] rounded-full pointer-events-none" />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Section id="contact-section" bordered>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
className="mb-16"
|
||||
eyebrow="GET IN TOUCH"
|
||||
title="도입 문의 및 컨택하기"
|
||||
description="사내 ERP 연동부터 우리 기업에 맞춘 흥정 시나리오 구성까지, negotium의 구매 혁신 컨설턴트가 상세히 안내해 드립니다."
|
||||
eyebrow="Get in Touch"
|
||||
title="도입 문의"
|
||||
description="품목과 협력사 규모를 알려주시면, 예상 절감 구간과 도입 절차를 정리해 드립니다."
|
||||
descriptionClassName="max-w-xl"
|
||||
/>
|
||||
|
||||
@@ -70,10 +74,10 @@ export function Contact() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -20 }}
|
||||
transition={{ duration: 0.5, ease: EASE_OUT_EXPO }}
|
||||
className="space-y-6"
|
||||
className="space-y-9"
|
||||
>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormField label="회사명" icon={Building} required>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-9">
|
||||
<FormField label="회사명" required>
|
||||
<Input
|
||||
type="text"
|
||||
name="companyName"
|
||||
@@ -98,8 +102,8 @@ export function Contact() {
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
|
||||
<FormField label="이메일 주소" icon={Mail} required>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-9">
|
||||
<FormField label="이메일 주소" required>
|
||||
<Input
|
||||
type="email"
|
||||
name="email"
|
||||
@@ -111,7 +115,7 @@ export function Contact() {
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField label="연락처" icon={Phone} required>
|
||||
<FormField label="연락처" required>
|
||||
<Input
|
||||
type="tel"
|
||||
name="phone"
|
||||
@@ -128,30 +132,34 @@ export function Contact() {
|
||||
<Textarea
|
||||
name="message"
|
||||
rows={4}
|
||||
placeholder="현재 겪고 계신 구매 조율 상의 번거로움이나, 자동화를 원하시는 구체적인 부자재 품목 정보를 남겨주시면 더욱 맞춤화된 상담이 가능합니다."
|
||||
placeholder="협상 자동화를 검토 중인 품목이나 현재 겪는 어려움을 적어주세요."
|
||||
value={formData.message}
|
||||
onChange={handleChange}
|
||||
disabled={submitting}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
{/* 대체 연락처(이메일 등)를 넣으려면 실제 영업 주소를 받아서 채워야 한다.
|
||||
임의의 주소를 공개 랜딩에 박아둘 수는 없다. */}
|
||||
{status === 'error' && (
|
||||
<p role="alert" className="text-[13px] text-ink-soft leading-[1.6] break-keep">
|
||||
지금은 접수가 어렵습니다. 잠시 후 다시 시도해 주세요.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Typography variant="caption" className="font-medium">
|
||||
* 제출 시 입력하신 정보는 문의 사항 응답 및 도입 검토 목적에 한하여 사용되며, 관련 법령에 의거하여 안전하게
|
||||
보호됩니다.
|
||||
입력하신 정보는 문의 응답과 도입 검토 목적으로만 사용됩니다.
|
||||
</Typography>
|
||||
|
||||
<div className="pt-2">
|
||||
<Button type="submit" disabled={submitting} className="w-full shadow-sm hover:shadow-md">
|
||||
<Button type="submit" disabled={submitting} size="lg" className="w-full">
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span>신청서 전송 중...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Send className="w-5 h-5" />
|
||||
<span>도입 문의 및 상담 신청하기</span>
|
||||
</>
|
||||
<span>상담 신청</span>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -162,15 +170,14 @@ export function Contact() {
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ duration: 0.6, ease: EASE_OUT_EXPO }}
|
||||
className="text-center py-16 px-6 bg-primary/5 rounded-[32px] text-ink break-keep"
|
||||
className="text-center py-20 px-6 border border-line-strong rounded-card text-ink break-keep"
|
||||
>
|
||||
<div className="w-16 h-16 bg-primary/10 text-primary rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<CheckCircle2 className="w-8 h-8" />
|
||||
<div className="w-12 h-12 bg-primary text-white rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<Check className="w-6 h-6" strokeWidth={2.5} />
|
||||
</div>
|
||||
<h3 className="text-2xl font-extrabold text-ink mb-3">도입 문의 신청이 접수되었습니다</h3>
|
||||
<p className="text-ink-soft font-semibold text-[15px] leading-relaxed max-w-md mx-auto mb-8">
|
||||
작성해주신 담당자 정보({formData.contactName} 님)를 통해 24시간 이내에 전담 혁신 컨설턴트가 유선 혹은 이메일로
|
||||
연락을 드리겠습니다.
|
||||
<h3 className="text-[24px] font-semibold tracking-[-0.02em] text-ink mb-3">도입 문의 신청이 접수되었습니다</h3>
|
||||
<p className="text-ink-soft text-[15px] leading-[1.6] max-w-md mx-auto mb-8">
|
||||
{formData.contactName} 님께 영업일 기준 하루 안에 연락드리겠습니다.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -190,22 +197,14 @@ export function Contact() {
|
||||
)
|
||||
}
|
||||
|
||||
function FormField({
|
||||
label,
|
||||
icon: Icon,
|
||||
required = false,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
icon?: LucideIcon
|
||||
required?: boolean
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
/* 라벨 옆 작은 아이콘은 정보를 더하지 않는다 — "회사명" 옆의 빌딩 아이콘이 알려주는 건
|
||||
이미 글자가 말한 것뿐이고, 필드마다 반복되면 폼이 산만해진다. 글자만 남긴다. */
|
||||
function FormField({ label, required = false, children }: { label: string; required?: boolean; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-ink-soft flex items-center gap-1.5">
|
||||
{Icon && <Icon className="w-3.5 h-3.5 text-ink-muted" />}
|
||||
{label} {required && <span className="text-primary">*</span>}
|
||||
<div className="space-y-2.5">
|
||||
<label className="block text-[14px] font-medium text-ink">
|
||||
{label}
|
||||
{required && <span className="text-primary ml-1" aria-hidden>*</span>}
|
||||
</label>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
@@ -12,13 +12,12 @@ export function CoreValues() {
|
||||
|
||||
return (
|
||||
<Section id="core-values">
|
||||
<motion.div {...fadeUp} className="mb-24">
|
||||
<motion.div {...fadeUp}>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
eyebrow="BEYOND EXPECTED VALUE"
|
||||
eyebrow="Beyond Price"
|
||||
title="가격 그 이상의 이점"
|
||||
description="절감액은 시작일 뿐 — 관계, 투명성, 그리고 사람의 시간까지 지킵니다."
|
||||
descriptionClassName="mt-4 text-[17px]"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
@@ -37,7 +36,7 @@ function ValueStrip({ value, delay }: { value: Value; delay: number }) {
|
||||
const fadeUp = useFadeUp(delay)
|
||||
|
||||
return (
|
||||
<motion.div {...fadeUp} className="bg-surface p-8 rounded-[32px] flex items-start gap-5 transition-all hover:translate-y-[-4px]">
|
||||
<motion.div {...fadeUp} className="bg-surface p-8 rounded-card flex items-start gap-5 transition-all hover:translate-y-[-4px]">
|
||||
<div className="w-10 h-10 rounded-full bg-primary/5 flex items-center justify-center text-primary shrink-0 mt-1">
|
||||
<value.icon className="w-5 h-5" />
|
||||
</div>
|
||||
@@ -56,7 +55,7 @@ const VALUES: Value[] = [
|
||||
icon: Users,
|
||||
title: "파트너사 관계 수호",
|
||||
description:
|
||||
"단가를 깎는 악역과 감정 소모는 봇이 맡습니다. 담당자는 협력사와의 신뢰와 동반 성장, 큰 틀의 파트너십에만 집중하세요.",
|
||||
"단가 조율은 에이전트가 정해진 기준으로 반복합니다. 담당자는 협력사와의 신뢰와 동반 성장에 집중할 수 있습니다.",
|
||||
},
|
||||
{
|
||||
icon: Lock,
|
||||
@@ -68,7 +67,7 @@ const VALUES: Value[] = [
|
||||
icon: Briefcase,
|
||||
title: "핵심 전략에만 집중",
|
||||
description:
|
||||
"이메일·메신저로 반복되던 흥정 수작업은 봇이 전담합니다. 인력은 공급망 위기 대처, 우량 공급처 발굴 같은 전략 업무와 대형 거래에 투입하세요.",
|
||||
"이메일·메신저로 오가던 단가 협의는 에이전트가 전담합니다. 인력은 공급망 위기 대응과 신규 공급처 발굴에 투입하세요.",
|
||||
},
|
||||
{
|
||||
icon: Clock,
|
||||
|
||||
@@ -14,13 +14,12 @@ export function Faq() {
|
||||
|
||||
return (
|
||||
<Section id="faq" width="sm">
|
||||
<motion.div {...fadeUp} className="mb-24">
|
||||
<motion.div {...fadeUp}>
|
||||
<SectionHeading
|
||||
align="center"
|
||||
eyebrow="FAQ"
|
||||
title="자주 묻는 질문"
|
||||
description="도입 검토에서 가장 많이 받는 질문들입니다."
|
||||
descriptionClassName="mt-4 text-[17px]"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
@@ -55,7 +54,7 @@ function FaqItem({
|
||||
const fadeUp = useFadeUp(delay)
|
||||
|
||||
return (
|
||||
<motion.div {...fadeUp} className="bg-surface rounded-[28px] overflow-hidden">
|
||||
<motion.div {...fadeUp} className="bg-surface rounded-card overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
@@ -96,14 +95,14 @@ function FaqItem({
|
||||
|
||||
const FAQS: FaqEntry[] = [
|
||||
{
|
||||
question: "공급사가 봇과의 협상을 싫어하지 않을까요?",
|
||||
question: "협력사가 에이전트와의 협상을 꺼리지 않을까요?",
|
||||
answer:
|
||||
"오히려 반대입니다. 이 거래들 대부분은 지금껏 협상 테이블에 오르지도 못하던 건입니다. 봇은 24시간 원하는 시간에, 압박 없이, 늘 같은 기준으로 응대합니다. 글로벌 동종 서비스의 공급사 만족도는 82%에 이릅니다.",
|
||||
"이 건들 대부분은 지금껏 협상 테이블에 오르지도 못하던 거래입니다. 에이전트는 협력사가 편한 시간에, 늘 같은 기준으로 응대합니다. 글로벌 동종 서비스의 공급사 만족도는 82%로 보고됩니다.",
|
||||
},
|
||||
{
|
||||
question: "봇이 우리 기준을 벗어나 합의해 버리면요?",
|
||||
question: "에이전트가 우리 기준을 벗어나 합의해 버리면요?",
|
||||
answer:
|
||||
"그럴 수 없습니다. 봇은 견적을 만들 때 정한 목표가와 낙찰 기준 밖으로 나가지 않고, 최종 낙찰 규칙도 사용자가 정합니다.",
|
||||
"그럴 수 없습니다. 에이전트는 견적을 만들 때 정한 목표가와 낙찰 기준 밖으로 나가지 않고, 최종 낙찰 규칙도 사용자가 정합니다.",
|
||||
},
|
||||
{
|
||||
question: "기존 시스템과 연동되나요?",
|
||||
|
||||
@@ -2,58 +2,71 @@ import { motion } from "motion/react"
|
||||
import { ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { NegotiationReplay } from "@/components/ui/negotiation-replay"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { CTA_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { useFadeUp } from "@/lib/motion"
|
||||
|
||||
/** 최종 CTA — 다크 몰입 섹션. */
|
||||
/**
|
||||
* 최종 CTA — 히어로와 같은 다크 무대로 페이지를 닫는다.
|
||||
*
|
||||
* 이 섹션은 원래 디자인 시스템을 우회하고 있었다: bg-ink(무대 색이 아님), font-extrabold,
|
||||
* 알약 배지, blur(120px) 글로우 블롭, 다크 배경 위 라이트 토큰(text-ink-muted).
|
||||
* 전부 토큰으로 돌렸다. 글로우 블롭은 AI 가 만든 히어로의 대표 장식이라 걷어냈다.
|
||||
*
|
||||
* 섹션 껍데기와 머리도 손으로 짜던 걸 Section/SectionHeading 으로 돌렸다.
|
||||
* 우회하는 동안 아이브로우 간격이 여기만 20px 이었다(다른 섹션은 12px).
|
||||
*
|
||||
* 전환을 요청하는 자리에 결과 화면을 같이 둔다. 이용 가이드는 "실제 화면으로 보여드립니다"
|
||||
* 라고 약속해서 재구성 목업을 넣을 수 없지만, 여기는 그 약속이 없어 마케팅 컴포짓이 맞는 자리다.
|
||||
*/
|
||||
export function FinalCTA() {
|
||||
return (
|
||||
<section className="relative bg-ink text-white py-36 md:py-48 overflow-hidden">
|
||||
{/* 다크 섹션 중앙의 은은한 파란 글로우 */}
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] rounded-full bg-primary/15 blur-[120px] pointer-events-none" />
|
||||
const fadeUp = useFadeUp()
|
||||
const mediaFadeUp = useFadeUp(0.12)
|
||||
|
||||
<div className="max-w-3xl mx-auto px-6 text-center relative z-10">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
whileInView={{ opacity: 1, scale: 1 }}
|
||||
viewport={{ once: true }}
|
||||
className="inline-flex items-center gap-2 px-4 py-1.5 bg-primary/10 border border-primary/20 rounded-full text-xs font-bold text-primary mb-8"
|
||||
>
|
||||
<span>START RECLAIMING YOUR BUDGET TODAY</span>
|
||||
return (
|
||||
/* 영상이 붙으면서 width 를 md(max-w-4xl) → lg(max-w-5xl) 로 넓혔다.
|
||||
세로 목업과 카피를 4xl 안에 2단으로 밀어넣으면 양쪽 다 좁아진다. */
|
||||
<Section bg="stage" width="lg">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-center">
|
||||
<motion.div {...fadeUp} className="lg:col-span-7 text-center lg:text-left">
|
||||
<SectionHeading
|
||||
align="left"
|
||||
className="text-center lg:text-left"
|
||||
tone="stage"
|
||||
size="display"
|
||||
gap="none"
|
||||
eyebrow="Start Today"
|
||||
/* 닫는 CTA 라 히어로(74px)보다는 낮추고 섹션 제목(64px)보다는 세운다.
|
||||
2단이 되면서 한 줄이 짧아져 lg 부터 한 단계 더 줄인다. */
|
||||
titleClassName="text-[32px] sm:text-[44px] md:text-[56px] lg:text-[48px]"
|
||||
title={
|
||||
<>
|
||||
<span className="text-white">지금도 구매 예산은</span>
|
||||
<br />
|
||||
<span className="text-on-stage-soft/60">조용히 새고 있을지 모릅니다</span>
|
||||
</>
|
||||
}
|
||||
description="협상 테이블에 오르지 못하고 그냥 넘어가던 건들이 있습니다. 네고시움 에이전트가 정해진 기준 안에서 그 건들을 대신 조율합니다."
|
||||
descriptionClassName="max-w-xl text-on-stage-soft/75 mx-auto lg:mx-0"
|
||||
/>
|
||||
|
||||
<div className={`${CTA_GAP} flex justify-center lg:justify-start`}>
|
||||
<Button href="#contact-section" variant="stage" size="xl" className="group">
|
||||
<span>도입 상담 신청</span>
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<motion.h2
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.8, delay: 0.1 }}
|
||||
className="text-3xl sm:text-4xl md:text-[54px] font-extrabold tracking-tighter mb-8 text-white leading-[1.2] break-keep"
|
||||
>
|
||||
지금도 구매 예산은 <br className="sm:hidden" />
|
||||
조용히 새고 있을지 모릅니다
|
||||
</motion.h2>
|
||||
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.8, delay: 0.2 }}
|
||||
className="text-[17px] text-ink-muted max-w-xl mx-auto mb-14 leading-relaxed font-semibold break-keep"
|
||||
>
|
||||
수작업으로 진행되어 수많은 단가 타협 기회를 흘려보내던 파트너사 흥정, 규칙 준수에 압도적으로 특화된 negotium 봇에
|
||||
위임하고 재무 마진을 안전히 지키십시오.
|
||||
</motion.p>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
whileInView={{ opacity: 1, y: 0 }}
|
||||
viewport={{ once: true }}
|
||||
transition={{ duration: 0.8, delay: 0.3 }}
|
||||
>
|
||||
<Button href="#contact-section" size="xl" className="gap-2.5 hover:-translate-y-px">
|
||||
<span>도입 및 계약 상담 신청하기</span>
|
||||
<ArrowRight className="w-5 h-5" />
|
||||
</Button>
|
||||
{/* 결과 화면. 예전엔 negotiation_annotated_3d.mp4 였는데 컴포넌트로 바꿨다 —
|
||||
영상은 화자("아이마켓 구매 MD")와 색이 픽셀에 구워져 있어 둘 다 못 고쳤다.
|
||||
다크 무대에 네이티브로 그리니 밝은 영상이 구멍처럼 뜨던 문제도 같이 사라져서,
|
||||
카드로 감싸고 그림자로 띄우던 처리가 더는 필요 없다. */}
|
||||
<motion.div {...mediaFadeUp} className="lg:col-span-5">
|
||||
<NegotiationReplay className="mx-auto max-w-[360px] lg:max-w-none" />
|
||||
</motion.div>
|
||||
</div>
|
||||
</section>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
@@ -8,7 +8,7 @@ export function Footer() {
|
||||
<div className="md:col-span-8">
|
||||
<Logo className="mb-6" />
|
||||
<Typography variant="caption" className="max-w-sm mb-6 font-medium">
|
||||
negotium은 협상 봇이 공급사와 1:1로 단가를 조율하고 낙찰까지 처리하는 B2B 구매 협상 자동화 솔루션입니다.
|
||||
네고시움은 협상 에이전트가 공급사와 1:1로 단가를 조율하고 낙찰까지 처리하는 B2B 구매 협상 자동화 솔루션입니다.
|
||||
</Typography>
|
||||
<p className="text-xs text-ink-faint font-semibold">
|
||||
© {new Date().getFullYear()} negotium Co., Ltd. All rights reserved.
|
||||
|
||||
@@ -5,36 +5,78 @@ import { Button } from "@/components/ui/button"
|
||||
import { Logo } from "@/components/ui/logo"
|
||||
|
||||
export function Header() {
|
||||
const [scrolled, setScrolled] = useState(false)
|
||||
// 두 상태는 조건이 다르다. 하나로 묶으면 다크 히어로 위에 흰 바가 떠버린다.
|
||||
// compact — 조금이라도 스크롤하면 높이를 줄인다.
|
||||
// onStage — 다크 히어로를 벗어나기 전까지. 이때는 배경을 깔지 않고 로고를 반전시킨다.
|
||||
const [compact, setCompact] = useState(false)
|
||||
const [onStage, setOnStage] = useState(true)
|
||||
|
||||
// 스크롤 시 헤더를 반투명 블러 배경으로 전환
|
||||
useEffect(() => {
|
||||
const handleScroll = () => setScrolled(window.scrollY > 40)
|
||||
const handleScroll = () => setCompact(window.scrollY > 40)
|
||||
window.addEventListener("scroll", handleScroll, { passive: true })
|
||||
handleScroll()
|
||||
return () => window.removeEventListener("scroll", handleScroll)
|
||||
}, [])
|
||||
|
||||
/* "다크 히어로 위에 있는가"는 스크롤 수치가 아니라 교차 상태다.
|
||||
scrollY 로 계산하면 하이드레이션 전에 스크롤 위치가 잡힌 경우(ScrollRestoration,
|
||||
새로고침, 뒤로가기) 초기 계산이 0 에서 끝나고 이후 스크롤 이벤트가 없으면
|
||||
영영 갱신되지 않는다 — 흰 배경 위에 흰 글자 버튼이 남는다.
|
||||
IntersectionObserver 는 관찰 시작 즉시 올바른 값을 준다. */
|
||||
useEffect(() => {
|
||||
const stage = document.querySelector("[data-stage-hero]")
|
||||
if (!stage) {
|
||||
setOnStage(false) // 다크 히어로가 없는 페이지에서는 항상 라이트
|
||||
return
|
||||
}
|
||||
// 헤더 높이(약 80px)만큼 위에서 미리 전환되도록 상단 마진을 음수로 준다.
|
||||
const io = new IntersectionObserver(([entry]) => setOnStage(entry.isIntersecting), {
|
||||
rootMargin: "-80px 0px 0px 0px",
|
||||
threshold: 0,
|
||||
})
|
||||
io.observe(stage)
|
||||
return () => io.disconnect()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<header
|
||||
className={`fixed top-0 left-0 right-0 z-40 safe-t safe-x transition-all duration-300 ${
|
||||
scrolled ? "py-4 bg-white/80 backdrop-blur-xl border-b border-line" : "py-6 bg-transparent border-b border-transparent"
|
||||
/* 배경은 "스크롤됐을 때"만 깔되, 무대 위에서는 흰색이 아니라 무대색으로 깐다.
|
||||
투명한 채로 두면 히어로 카피가 헤더 밑으로 지나가며 nav 글자와 겹쳐 읽힌다. */
|
||||
className={`fixed top-0 left-0 right-0 z-40 safe-t safe-x transition-all duration-300 ${compact ? "py-4" : "py-6"} ${
|
||||
!compact
|
||||
? "bg-transparent border-b border-transparent"
|
||||
: onStage
|
||||
? "bg-stage/80 backdrop-blur-xl border-b border-stage-line"
|
||||
: "bg-white/80 backdrop-blur-xl border-b border-line"
|
||||
}`}
|
||||
>
|
||||
<div className="max-w-5xl mx-auto px-6 flex items-center justify-between">
|
||||
<a href="#">
|
||||
<Logo />
|
||||
<Logo className={onStage ? "brightness-0 invert" : undefined} />
|
||||
</a>
|
||||
|
||||
<nav className="hidden md:flex items-center gap-8 text-[15px] font-semibold text-ink-soft">
|
||||
<nav
|
||||
className={`hidden md:flex items-center gap-8 text-[15px] font-semibold transition-colors ${
|
||||
onStage ? "text-on-stage-soft" : "text-ink-soft"
|
||||
}`}
|
||||
>
|
||||
{NAV_LINKS.map(({ href, label }) => (
|
||||
<a key={href} href={href} className="hover:text-ink transition-colors">
|
||||
<a
|
||||
key={href}
|
||||
href={href}
|
||||
className={`transition-colors ${onStage ? "hover:text-on-stage" : "hover:text-ink"}`}
|
||||
>
|
||||
{label}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<Button href="#contact-section" size="pill" className="gap-1.5">
|
||||
<Button
|
||||
href="#contact-section"
|
||||
variant={onStage ? "stageGhost" : "primary"}
|
||||
size={onStage ? "stageRound" : "pill"}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<span>상담 신청</span>
|
||||
<ArrowUpRight className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowDown, ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
/** 히어로 변형 — 실시간 협상 콘솔 시즐 영상을 전면에 세운 풀와이드 히어로. */
|
||||
export function HeroConsole() {
|
||||
return (
|
||||
<section className="relative min-h-screen bg-surface-neu text-ink flex flex-col justify-center pt-32 pb-20 overflow-hidden">
|
||||
<div className="mesh-bg absolute top-[-260px] left-[-160px] opacity-40 pointer-events-none" />
|
||||
|
||||
<div className="max-w-6xl mx-auto px-6 w-full relative z-10">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 28, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ duration: 0.8, delay: 0.1 }}
|
||||
className="rounded-[28px] overflow-hidden border border-line-strong shadow-[0_30px_80px_rgba(20,25,45,0.12)] bg-white"
|
||||
>
|
||||
<video
|
||||
src="/gifs/hero_console.mp4"
|
||||
poster="/gifs/hero_console.jpg"
|
||||
autoPlay
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
className="w-full h-auto block"
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.8, delay: 0.35 }}
|
||||
className="flex flex-col sm:flex-row justify-center gap-5 pt-10"
|
||||
>
|
||||
<Button
|
||||
href="#contact-section"
|
||||
className="w-full sm:w-auto group shadow-[0_8px_24px_rgba(49,130,246,0.15)] hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
<span>도입 문의 상담 받기</span>
|
||||
<ArrowRight className="w-5 h-5 transition-transform group-hover:translate-x-1" />
|
||||
</Button>
|
||||
<Button href="#how-it-works" variant="glass" className="w-full sm:w-auto gap-1.5">
|
||||
<span>작동 방식 보기</span>
|
||||
<ArrowDown className="w-4 h-4 text-ink-soft" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useState } from "react"
|
||||
import { ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DemoRequestModal } from "@/components/ui/demo-request-modal"
|
||||
import { CTA_GAP, DISPLAY_LEAD_GAP } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/**
|
||||
* 다크 무대 히어로 — 배경 루프 영상.
|
||||
*
|
||||
* 예전에는 캔버스가 negotium 파이프라인을 직접 그렸고(입자 240개·6단계 서사·무리 라벨),
|
||||
* 배경이 곧 설명이었다. 지금은 배경을 배경으로만 쓴다 — 설명은 카피와 아래 섹션이 맡는다.
|
||||
* 그래서 무리 라벨(CLUSTER_ANCHORS)도 함께 걷어냈다. 좌표 소스가 사라진 라벨은
|
||||
* 화면비가 바뀔 때마다 어긋나기만 하고 아무것도 설명하지 못한다.
|
||||
*
|
||||
* 배경이 의미를 지지 않으므로 카피 가독성이 1순위다. 그래서:
|
||||
* - 영상 위에 스크림을 깐다. 예전 캔버스는 하단 밴드에만 입자가 있어 상단이 비었지만,
|
||||
* 이 영상은 화면 전체에 밝은 요소가 흩어져 흰 글자가 묻힌다.
|
||||
* - 카피는 화면 중앙 정렬. 밴드 개념이 없으니 상하로 나눌 이유도 없다.
|
||||
*/
|
||||
export function HeroDataFlow() {
|
||||
const [demoOpen, setDemoOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<section
|
||||
data-stage-hero
|
||||
className="stage-bg relative min-h-screen text-on-stage flex flex-col overflow-hidden"
|
||||
>
|
||||
{/* 영상은 가로 화면에서만 튼다.
|
||||
16:9 소스를 세로 화면에 object-cover 로 깔면 가로가 62% 잘리고 남은 38% 가
|
||||
1.7배로 확대된다(848x1220 실측) — 데이터 입자가 거대한 보케로 뭉개져서
|
||||
배경이 아니라 노이즈가 된다. 캔버스는 뷰포트에 맞춰 그렸으니 없던 문제다.
|
||||
세로에서는 무대 그라데이션(stage-bg)만 남긴다. 그게 브랜드 배경이라 빈 화면이 아니다.
|
||||
prefers-reduced-motion 에서도 같은 이유로 영상을 감춘다 — 포스터가 뒤를 받친다. */}
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute inset-0 hidden landscape:block motion-reduce:hidden bg-cover bg-center"
|
||||
style={{ backgroundImage: "url(/gifs/hero_loop.jpg)" }}
|
||||
>
|
||||
<video
|
||||
className="w-full h-full object-cover"
|
||||
src="/gifs/hero_loop.mp4"
|
||||
poster="/gifs/hero_loop.jpg"
|
||||
autoPlay
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
preload="metadata"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 카피 가독성용 스크림.
|
||||
색은 하나(stage-deep)로 두고 알파만 움직인다 — 중간 stop 에서 색이 바뀌면
|
||||
그 지점이 가로선으로 읽힌다.
|
||||
|
||||
알파는 90/60/95 였다가 낮췄다. 그 값은 헤드라인 둘째 줄이 회색(/60)이던 시절
|
||||
그 글자를 살리려고 깐 것인데, 가장 옅은 지점에서도 영상이 40% 만 남아서
|
||||
배경 전체가 탁해졌다. 헤드라인이 흰색이 된 지금은 이만큼 덮을 이유가 없다.
|
||||
구간별로 필요한 만큼만 준다 — 위는 헤더 nav(작은 회색 글자), 가운데는 흰
|
||||
헤드라인이라 가장 옅게, 아래는 다음 섹션으로 넘어가는 암전(h-32)이 따로 있다. */}
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute inset-0 pointer-events-none bg-linear-to-b from-stage-deep/50 via-transparent to-stage-deep/45"
|
||||
/>
|
||||
|
||||
{/* 카피 뒤만 국소적으로 누른다.
|
||||
전면을 균일하게 덮으면 글자는 살지만 영상이 통째로 탁해진다. 반대로 다 걷으면
|
||||
헤드라인(흰색 74px)은 버텨도 리드 문단(17px)이 밝은 입자 위에서 읽히지 않는다.
|
||||
둘 다 만족하는 유일한 방법은 덮는 범위를 글자가 있는 자리로 좁히는 것이다.
|
||||
가장자리는 영상이 그대로 보이고 가운데만 어두워진다. */}
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute inset-0 pointer-events-none"
|
||||
style={{
|
||||
background:
|
||||
"radial-gradient(58% 42% at 50% 45%," +
|
||||
" color-mix(in srgb, var(--color-stage-deep) 85%, transparent) 0%," +
|
||||
" color-mix(in srgb, var(--color-stage-deep) 55%, transparent) 45%," +
|
||||
" transparent 72%)",
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 아래 라이트 섹션과의 경계를 부드럽게 */}
|
||||
<div aria-hidden className="absolute inset-x-0 bottom-0 h-32 bg-linear-to-b from-transparent to-stage pointer-events-none" />
|
||||
|
||||
{/* pt-[104px] 는 fixed 헤더 회피용 바닥. 그 아래 남은 공간에서 수직 중앙 정렬한다. */}
|
||||
<div className="relative z-10 w-full flex-1 pt-[104px] pb-16 flex items-center">
|
||||
<div className="max-w-4xl mx-auto px-6 w-full text-center">
|
||||
{/* 히어로 카피에는 진입 애니메이션을 걸지 않는다.
|
||||
여기가 LCP 요소라 opacity:0 으로 시작하면 하이드레이션 전까지 첫 화면이 비고,
|
||||
광고 유입처럼 JS 가 느린 환경에서 그대로 손실이 된다. 모션은 배경 영상이 맡는다. */}
|
||||
{/* 여기는 2톤을 쓰지 않는다. 예전 캔버스 배경은 하단 밴드에만 입자가 있어 헤드라인
|
||||
뒤가 거의 단색이었고, 그때는 투명도 60% 로 낮춘 둘째 줄도 읽혔다. 배경이 영상으로
|
||||
바뀌면서 밝은 요소가 글자 뒤로 지나가 그 대비가 무너졌다 — 배경이 움직이는 위에서는
|
||||
가독성이 조판 장치보다 우선한다. 2톤은 최종 CTA 에 남아 있다(그쪽은 배경이 정적). */}
|
||||
<Typography variant="stageDisplay">
|
||||
<span className="text-white">협력사 전원과 1:1로,</span>
|
||||
<br />
|
||||
<span className="text-white">동시에 협상합니다.</span>
|
||||
</Typography>
|
||||
|
||||
{/* 히어로는 h1 이어야 해서 SectionHeading(h2 고정)을 못 쓴다. 대신 간격만은
|
||||
같은 상수를 물려 최종 CTA 와 리듬이 어긋나지 않게 한다. */}
|
||||
<p className={`${DISPLAY_LEAD_GAP} text-base sm:text-lg text-on-stage-soft leading-relaxed break-keep max-w-2xl mx-auto`}>
|
||||
품목·목표가·마감일만 정하면 됩니다. 협상 에이전트가 협력사마다 따로 붙어 단가를 조율하고, 마감 시각에
|
||||
최저 투찰가로 낙찰까지 판정합니다.
|
||||
</p>
|
||||
|
||||
{/* 2차 CTA 는 상담 신청(#contact-section)과 목적지가 겹쳐 사실상 같은 버튼이었다.
|
||||
데모 경로로 갈라서, 고관여 폼(상담 신청) 앞단에 저관여 리드 캡처를 둔다.
|
||||
|
||||
문구는 "클릭하면 무슨 일이 일어나는가"에 맞춘다.
|
||||
협상 예시 체험 — 페이지 안에서 바로 조작한다. 고정 데이터라 "예시"를 밝히되,
|
||||
도착 섹션이 "직접 경험해 보세요"·"해보기" 라 "보기"로 낮추면 어긋난다.
|
||||
실제 데모 받기 — 누르면 폼이 뜨고 이메일로 온다. "체험"이라 쓰면 눌렀을 때
|
||||
바로 만질 줄 알았다가 입력을 요구받아 낚인 느낌이 된다. */}
|
||||
<div className={`${CTA_GAP} flex flex-col sm:flex-row gap-3 justify-center`}>
|
||||
<Button href="#how-it-works" variant="stage" size="stageRound" className="group">
|
||||
<span>협상 예시 체험</span>
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</Button>
|
||||
<Button type="button" variant="stageGhost" size="stageRound" onClick={() => setDemoOpen(true)}>
|
||||
실제 데모 받기
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DemoRequestModal open={demoOpen} onClose={() => setDemoOpen(false)} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowDown, ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
|
||||
/** 기본 히어로 — 파스텔 블롭 + 그리드 + 떠다니는 와이어프레임 도형. */
|
||||
export function HeroGlassmorphic() {
|
||||
return (
|
||||
<section className="relative min-h-screen bg-surface text-ink flex flex-col justify-center pt-32 overflow-hidden">
|
||||
{/* 흐릿한 파스텔 블롭 배경 */}
|
||||
<div className="absolute top-[10%] right-[15%] w-[480px] h-[480px] bg-primary/10 rounded-full filter blur-[120px] pointer-events-none" />
|
||||
<div className="absolute bottom-[10%] left-[10%] w-[450px] h-[450px] bg-accent/10 rounded-full filter blur-[120px] pointer-events-none" />
|
||||
<div className="absolute top-[30%] left-[30%] w-[380px] h-[380px] bg-primary/10 rounded-full filter blur-[100px] pointer-events-none" />
|
||||
|
||||
{/* 저채도 그리드 패턴 오버레이 */}
|
||||
<div className="absolute inset-0 bg-[linear-gradient(rgba(0,0,0,0.01)_1px,transparent_1px),linear-gradient(90deg,rgba(0,0,0,0.01)_1px,transparent_1px)] bg-[size:40px_40px] pointer-events-none" />
|
||||
|
||||
{/* 떠다니는 와이어프레임 도형 — max-w-7xl 안에 가둠 */}
|
||||
<div className="absolute inset-0 max-w-7xl mx-auto pointer-events-none z-0">
|
||||
<motion.div
|
||||
animate={{ y: [0, -18, 0], rotate: [12, 42, 12] }}
|
||||
transition={{ duration: 8, repeat: Infinity, ease: "easeInOut" }}
|
||||
className="absolute top-[15%] left-[8vw] lg:left-[10%] w-16 h-16 sm:w-28 sm:h-28 border-2 border-primary/40 bg-white/40 shadow-[0_8px_32px_rgba(49,130,246,0.05)] rounded-[28px] pointer-events-none z-0"
|
||||
/>
|
||||
<motion.div
|
||||
animate={{ rotate: -360 }}
|
||||
transition={{ duration: 80, repeat: Infinity, ease: "linear" }}
|
||||
className="absolute bottom-[18%] left-[6vw] lg:left-[12%] w-28 h-28 sm:w-48 sm:h-48 border-2 border-dashed border-accent/30 rounded-full pointer-events-none z-0"
|
||||
/>
|
||||
<motion.div
|
||||
animate={{ x: [0, 10, 0], y: [0, 10, 0] }}
|
||||
transition={{ duration: 10, repeat: Infinity, ease: "easeInOut" }}
|
||||
className="absolute top-[30%] right-[8vw] lg:right-[12%] w-20 h-20 sm:w-36 sm:h-36 border-2 border-primary/20 rounded-[40px] pointer-events-none z-0"
|
||||
>
|
||||
<div className="w-full h-full bg-gradient-to-tr from-primary/5 to-transparent rounded-[38px]" />
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto px-6 w-full py-24 relative z-10 flex flex-col items-center text-center">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.9, delay: 0.1, ease: EASE_OUT_EXPO }}
|
||||
>
|
||||
<Typography variant="display" className="mb-8">
|
||||
구매 협상, 이제 <span className="text-primary">봇이 알아서</span> <br className="hidden sm:inline" />
|
||||
흥정부터 낙찰까지 자동으로
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.9, delay: 0.2, ease: EASE_OUT_EXPO }}
|
||||
>
|
||||
<Typography variant="lead" className="md:text-[20px] max-w-2xl mb-12">
|
||||
협상할수록 강화학습으로 흥정 전략을 알아서 다듬어갑니다. <br className="hidden sm:inline" />
|
||||
감정 없이, 지치지 않고, 24시간 연중무휴 — 결렬 대신 성사로 이끕니다.
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 24 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.9, delay: 0.3, ease: EASE_OUT_EXPO }}
|
||||
className="flex flex-col sm:flex-row gap-4 items-center justify-center w-full max-w-md z-20"
|
||||
>
|
||||
<Button
|
||||
href="#contact-section"
|
||||
className="w-full sm:w-auto group shadow-[0_8px_24px_rgba(49,130,246,0.15)] hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
<span>도입 문의 상담 받기</span>
|
||||
<ArrowRight className="w-5 h-5 transition-transform group-hover:translate-x-1" />
|
||||
</Button>
|
||||
<Button href="#how-it-works" variant="glass" className="w-full sm:w-auto gap-1.5">
|
||||
<span>작동 방식 보기</span>
|
||||
<ArrowDown className="w-4 h-4 text-ink-soft" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowDown, ArrowRight } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/** 대안 히어로 — 뉴모피즘 배경 + 실제 모바일 협상 화면(GIF) 폰 목업. */
|
||||
export function HeroNeumorphic() {
|
||||
return (
|
||||
<section className="relative min-h-screen bg-surface-neu text-ink flex flex-col justify-center pt-32 pb-20 overflow-hidden">
|
||||
{/* 우측 상단 메시 제거 — 영상 배경(#F2F4F7)과 섹션 배경을 완전 동일하게 유지해 경계선 없이 블렌딩 */}
|
||||
|
||||
<div className="max-w-5xl mx-auto px-6 w-full relative z-10 grid grid-cols-1 lg:grid-cols-12 gap-16 items-center">
|
||||
{/* 좌: 카피 + CTA */}
|
||||
<div className="lg:col-span-7 space-y-8 text-left">
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.8, delay: 0.1 }}>
|
||||
<Typography variant="display" className="text-4xl sm:text-5xl lg:text-[54px] leading-[1.15]">
|
||||
구매 협상, <br />
|
||||
이제 <span className="text-primary">봇이 알아서</span> <br />
|
||||
흥정부터 낙찰까지 자동으로
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.8, delay: 0.2 }}>
|
||||
<Typography variant="lead" className="max-w-xl">
|
||||
불필요한 실랑이와 감정 소모 없이, 예산 상한선 내에서 최적의 원가 절감을 달성하세요. 데이터 기반의 자율 흥정 봇이
|
||||
24시간 실시간 대리 협상을 완료합니다.
|
||||
</Typography>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.8, delay: 0.3 }}
|
||||
className="flex flex-col sm:flex-row gap-5 pt-4"
|
||||
>
|
||||
<Button
|
||||
href="#contact-section"
|
||||
className="w-full sm:w-auto group shadow-[0_8px_24px_rgba(49,130,246,0.15)] hover:scale-[1.02] active:scale-[0.98]"
|
||||
>
|
||||
<span>도입 문의 상담 받기</span>
|
||||
<ArrowRight className="w-5 h-5 transition-transform group-hover:translate-x-1" />
|
||||
</Button>
|
||||
<Button href="#how-it-works" variant="glass" className="w-full sm:w-auto gap-1.5">
|
||||
<span>작동 방식 보기</span>
|
||||
<ArrowDown className="w-4 h-4 text-ink-soft" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* 우: 모바일 협상 채팅 + 외부 설명 UI(제안가·협상카드·낙찰 하이라이트) 합성 영상 */}
|
||||
<div className="lg:col-span-5 flex justify-center">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ duration: 0.8, delay: 0.2 }}
|
||||
className="w-full flex justify-center"
|
||||
>
|
||||
<video
|
||||
src="/gifs/negotiation_annotated_3d.mp4?v=w3"
|
||||
poster="/gifs/negotiation_annotated_3d.jpg?v=w3"
|
||||
autoPlay
|
||||
muted
|
||||
loop
|
||||
playsInline
|
||||
className="w-full max-w-[440px] h-auto"
|
||||
/>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Bot, Check, Monitor, Smartphone, Sparkles, type LucideIcon } from "lucide-react"
|
||||
import { Check, Monitor, Smartphone, type LucideIcon } from "lucide-react"
|
||||
|
||||
import { BrowserFrame, PhoneFrame } from "@/components/ui/device-mockups"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { CONTROL_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/** 3단계 이용 가이드 — 탭 전환식 GIF 시연 (데스크톱/모바일 목업). */
|
||||
@@ -17,21 +17,20 @@ export function HowItWorksDemo() {
|
||||
<Section id="how-it-works-demo" width="lg" bordered className="overflow-hidden">
|
||||
<SectionHeading
|
||||
align="center"
|
||||
className="mb-20"
|
||||
eyebrow="SERVICE DEMONSTRATION"
|
||||
eyebrow="How it Works"
|
||||
title="견적 생성부터 낙찰까지 한눈에 보기"
|
||||
description="복잡해 보이는 구매 과정이 어떻게 자동화되는지 실제 작동 화면(GIF)을 통해 쉽고 직관적으로 확인해 보세요."
|
||||
descriptionClassName="text-[17px] max-w-2xl"
|
||||
description="견적을 열고 협상이 끝나기까지, 실제 화면으로 보여드립니다."
|
||||
descriptionClassName="max-w-2xl"
|
||||
/>
|
||||
|
||||
{/* 탭 스위치 */}
|
||||
<div className="flex justify-center mb-16">
|
||||
<div className="p-1 bg-fill rounded-[14px] inline-flex flex-wrap justify-center gap-1">
|
||||
{/* 탭 스위치 — 비교 섹션 토글과 같은 간격 규칙(본문 쪽에 묶인다) */}
|
||||
<div className={`flex justify-center ${CONTROL_GAP}`}>
|
||||
<div className="p-1 bg-fill rounded-control inline-flex flex-wrap justify-center gap-1">
|
||||
{DEMO_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
onClick={() => setActiveKey(tab.key)}
|
||||
className={`px-5 py-2.5 rounded-[10px] text-xs sm:text-sm font-bold transition-all flex items-center gap-2 cursor-pointer ${
|
||||
className={`px-5 py-2.5 rounded-control text-xs sm:text-sm font-bold transition-all flex items-center gap-2 cursor-pointer ${
|
||||
activeKey === tab.key ? "bg-white text-primary" : "text-ink-soft hover:text-ink"
|
||||
}`}
|
||||
>
|
||||
@@ -54,10 +53,9 @@ export function HowItWorksDemo() {
|
||||
transition={{ duration: 0.4 }}
|
||||
className="space-y-6"
|
||||
>
|
||||
<div className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-bold ${activeTab.badge.className}`}>
|
||||
<activeTab.badge.icon className="w-3.5 h-3.5" />
|
||||
{activeTab.badge.label}
|
||||
</div>
|
||||
{/* 알약 배경 + 아이콘을 뺀 글자만의 라벨.
|
||||
레퍼런스 라벨은 11px/600/자간 normal 에 배경도 아이콘도 없다. */}
|
||||
<div className={`text-[11px] font-semibold ${activeTab.badge.className}`}>{activeTab.badge.label}</div>
|
||||
<Typography variant="heading">{activeTab.heading}</Typography>
|
||||
{activeTab.paragraphs.map((paragraph, idx) => (
|
||||
<Typography key={idx} variant="body">
|
||||
@@ -159,7 +157,7 @@ type DemoTab = {
|
||||
key: "create" | "negotiate" | "result"
|
||||
tabIcon: LucideIcon
|
||||
tabLabel: string
|
||||
badge: { icon: LucideIcon; label: string; className: string }
|
||||
badge: { label: string; className: string }
|
||||
checkClassName: string
|
||||
heading: React.ReactNode
|
||||
paragraphs: React.ReactNode[]
|
||||
@@ -183,19 +181,19 @@ const DEMO_TABS: DemoTab[] = [
|
||||
{
|
||||
key: "create",
|
||||
tabIcon: Monitor,
|
||||
tabLabel: "1단계: AI 견적 & 가이드 수립",
|
||||
badge: { icon: Sparkles, label: "구매 관리자 콘솔 (웹)", className: "bg-primary-soft text-primary" },
|
||||
tabLabel: "1. 견적 · 기준 수립",
|
||||
badge: { label: "구매 관리자 콘솔", className: "text-primary" },
|
||||
checkClassName: "text-primary",
|
||||
heading: (
|
||||
<>
|
||||
엑셀 등록만으로 끝나는 <br />
|
||||
초정밀 가이드라인 자율 수립
|
||||
엑셀만 올리면 <br />
|
||||
목표 단가가 잡힙니다
|
||||
</>
|
||||
),
|
||||
paragraphs: [
|
||||
<>
|
||||
품목명과 시중 시장 가격을 입력하면, negotium이 <b>인터넷 최저가(LPS)</b> 데이터를 상시 반영해{" "}
|
||||
<b className="text-primary">시장 바닥값을 쥐고 시작합니다.</b>
|
||||
품목명과 시중 시장 가격을 입력하면, 네고시움이 <b>인터넷 최저가(LPS)</b> 데이터를 상시 반영해{" "}
|
||||
<b className="text-primary">시장 최저가를 기준으로 시작합니다.</b>
|
||||
</>,
|
||||
<>
|
||||
시중 최저가와 매입 이력, 목표 마진율을 종합해 — 사내 마진은 지키면서 공급사가 받아들일 수 있는{" "}
|
||||
@@ -211,7 +209,7 @@ const DEMO_TABS: DemoTab[] = [
|
||||
gifAlt: "견적 생성 가이드라인 수립 시연",
|
||||
fallback: {
|
||||
icon: Monitor,
|
||||
iconWrapClassName: "w-14 h-14 bg-primary-soft rounded-2xl text-primary",
|
||||
iconWrapClassName: "w-14 h-14 bg-primary-soft rounded-card text-primary",
|
||||
codeClassName: "bg-white text-primary",
|
||||
title: "견적 생성 시연 GIF 공간",
|
||||
hint: "실제 기동 GIF를 배치하시면 이 영역에 자동으로 재생됩니다.",
|
||||
@@ -220,8 +218,8 @@ const DEMO_TABS: DemoTab[] = [
|
||||
{
|
||||
key: "negotiate",
|
||||
tabIcon: Smartphone,
|
||||
tabLabel: "2단계: AI 자동 밀당 협상",
|
||||
badge: { icon: Bot, label: "협력사 협상 포털 (웹·모바일)", className: "bg-positive-soft border border-positive/15 text-positive" },
|
||||
tabLabel: "2. 협력사별 1:1 협상",
|
||||
badge: { label: "협력사 협상 포털", className: "text-positive" },
|
||||
checkClassName: "text-positive",
|
||||
heading: (
|
||||
<>
|
||||
@@ -234,14 +232,18 @@ const DEMO_TABS: DemoTab[] = [
|
||||
각 파트너사 담당자는 초대 메일로 <b>비대면 협상 모바일 포털</b>에 접속해, 언제든 단가를 조율합니다.
|
||||
</>,
|
||||
<>
|
||||
단순 마진 깎기가 아닙니다. 봇은 준비된 협상 카드를 상황에 맞게 꺼내, 파트너사의 자발적인 마진 타협을 부드럽게
|
||||
단순히 깎는 게 아닙니다. 에이전트는 준비된 협상 카드를 상황에 맞게 꺼내, 협력사가 받아들일 조건을
|
||||
이끌어냅니다.
|
||||
</>,
|
||||
],
|
||||
checks: ["1:1 비대면 협상 포털 제공", "불필요한 실랑이를 예방하여 파트너십 보호"],
|
||||
checks: ["협력사별 1:1 비대면 협상 포털", "같은 기준으로 응대해 관계 부담 없음"],
|
||||
mockup: "phone",
|
||||
/* mp4 를 붙이기 전까지 이 탭만 1.7MB GIF(390x780)를 내려받고 있었다. 같은 내용의
|
||||
mp4 가 저장소에 있는데 참조가 빠져 있었다 — 786K, 540x1080 으로 더 가볍고 더 크다.
|
||||
(원본 캡쳐가 좌우로 잘려 문장이 끊기는 문제는 남아 있다. 재촬영이 필요하다.) */
|
||||
gif: "/gifs/negotiation.gif",
|
||||
gifAlt: "AI 모바일 자동 협상 시연",
|
||||
video: "/gifs/negotiation.mp4",
|
||||
gifAlt: "협력사 포털 모바일 협상 화면",
|
||||
fallback: {
|
||||
icon: Smartphone,
|
||||
iconWrapClassName: "w-12 h-12 bg-positive-soft border border-positive/15 rounded-full text-positive",
|
||||
@@ -254,7 +256,7 @@ const DEMO_TABS: DemoTab[] = [
|
||||
key: "result",
|
||||
tabIcon: Monitor,
|
||||
tabLabel: "3단계: AI 협상 결과 확인",
|
||||
badge: { icon: Monitor, label: "구매 관리자 콘솔 (웹)", className: "bg-accent-soft border border-accent/15 text-accent" },
|
||||
badge: { label: "구매 관리자 콘솔", className: "text-accent" },
|
||||
checkClassName: "text-accent",
|
||||
heading: (
|
||||
<>
|
||||
@@ -280,7 +282,7 @@ const DEMO_TABS: DemoTab[] = [
|
||||
gifAlt: "협상 결과 분석 대시보드 시연",
|
||||
fallback: {
|
||||
icon: Monitor,
|
||||
iconWrapClassName: "w-14 h-14 bg-accent-soft rounded-2xl text-accent",
|
||||
iconWrapClassName: "w-14 h-14 bg-accent-soft rounded-card text-accent",
|
||||
codeClassName: "bg-white text-accent",
|
||||
title: "협상 결과 확인 시연 GIF 공간",
|
||||
hint: "결과 보고 대시보드 기동 GIF를 배치하시면 이 영역에 자동으로 재생됩니다.",
|
||||
|
||||
@@ -1,324 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { AnimatePresence, motion } from "motion/react"
|
||||
import { Bot, Handshake, ShieldCheck } from "lucide-react"
|
||||
|
||||
import { PriceSparkline } from "@/components/ui/price-sparkline"
|
||||
import { SlateRenderer } from "@/components/ui/slate-renderer"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import type { DialogueStep } from "@/types"
|
||||
|
||||
/** 스크롤 연동 sticky 협상 데모 — 스크롤 진행률에 따라 대화가 쌓이고 단가가 내려간다. */
|
||||
export function NegotiationConsole() {
|
||||
// -1 = 아직 섹션 진입 전(온보딩 가이드 표시)
|
||||
const [activeStep, setActiveStep] = useState(-1)
|
||||
const [animatedPrice, setAnimatedPrice] = useState(1200000)
|
||||
const sectionRef = useRef<HTMLDivElement>(null)
|
||||
const chatContainerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// 섹션 내 스크롤 진행률 → 대화 스텝 매핑
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
if (!sectionRef.current) return
|
||||
const rect = sectionRef.current.getBoundingClientRect()
|
||||
const totalScrollable = rect.height - window.innerHeight
|
||||
if (totalScrollable <= 0) return
|
||||
|
||||
const scrolled = -rect.top
|
||||
if (scrolled < 0) {
|
||||
setActiveStep(-1)
|
||||
return
|
||||
}
|
||||
|
||||
const clampedRatio = Math.max(0, Math.min(scrolled / totalScrollable, 0.99))
|
||||
setActiveStep(Math.floor(clampedRatio * NEGOTIATION_STEPS.length))
|
||||
}
|
||||
|
||||
window.addEventListener("scroll", handleScroll, { passive: true })
|
||||
handleScroll()
|
||||
return () => window.removeEventListener("scroll", handleScroll)
|
||||
}, [])
|
||||
|
||||
// 단가 오도미터 애니메이션 (500ms ease-out)
|
||||
useEffect(() => {
|
||||
const targetPrice = activeStep === -1 ? 1200000 : NEGOTIATION_STEPS[activeStep].price
|
||||
if (animatedPrice === targetPrice) return
|
||||
|
||||
const start = animatedPrice
|
||||
const duration = 500
|
||||
const startTime = performance.now()
|
||||
|
||||
const animate = (currentTime: number) => {
|
||||
const progress = Math.min((currentTime - startTime) / duration, 1)
|
||||
const easeProgress = progress * (2 - progress)
|
||||
setAnimatedPrice(Math.round(start + (targetPrice - start) * easeProgress))
|
||||
if (progress < 1) requestAnimationFrame(animate)
|
||||
}
|
||||
|
||||
requestAnimationFrame(animate)
|
||||
}, [activeStep])
|
||||
|
||||
// 새 말풍선이 붙으면 채팅 영역을 바닥으로 스크롤
|
||||
useEffect(() => {
|
||||
chatContainerRef.current?.scrollTo({ top: chatContainerRef.current.scrollHeight, behavior: "smooth" })
|
||||
}, [activeStep])
|
||||
|
||||
return (
|
||||
<section
|
||||
id="how-it-works"
|
||||
ref={sectionRef}
|
||||
className="relative bg-surface text-ink w-full font-sans border-t border-line h-[240vh] md:h-[280vh]"
|
||||
>
|
||||
<div className="sticky top-0 h-screen flex items-center justify-center w-full overflow-hidden px-6 md:px-8">
|
||||
{/* 섹션 헤딩 — sticky 상단 고정 (모바일은 공간상 생략) */}
|
||||
<div className="absolute top-24 left-0 right-0 text-center hidden md:block">
|
||||
<Typography variant="eyebrow" className="block">
|
||||
Live Replay
|
||||
</Typography>
|
||||
<Typography variant="heading" as="h2" className="mt-1">
|
||||
봇은 물러서지 않습니다
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="max-w-4xl mx-auto grid grid-cols-1 md:grid-cols-12 gap-12 md:gap-16 items-center w-full">
|
||||
{/* 좌: 실시간 단가 패널 */}
|
||||
<div className="md:col-span-5 flex flex-col justify-center space-y-6 text-center md:text-left">
|
||||
<div>
|
||||
<span className="text-[11px] font-bold text-ink-muted uppercase tracking-wider block mb-1">실시간 협상 단가</span>
|
||||
<div className="flex items-baseline gap-1.5 justify-center md:justify-start">
|
||||
<span className="text-3xl font-bold text-primary">₩</span>
|
||||
<span className="text-4xl md:text-5xl font-black tracking-tight text-primary">
|
||||
{animatedPrice.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
{/* 시작가 대비 누적 절감 델타 — 높이 고정으로 레이아웃 점프 방지 */}
|
||||
<div className="h-6 mt-1.5">
|
||||
{animatedPrice < START_PRICE && (
|
||||
<span className="inline-flex items-baseline gap-1.5 text-positive font-bold text-sm">
|
||||
▼ {(START_PRICE - animatedPrice).toLocaleString()}원
|
||||
<span className="text-xs font-semibold">
|
||||
(−{(((START_PRICE - animatedPrice) / START_PRICE) * 100).toFixed(1)}%)
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 계단식 하락 스파크라인 + 목표가 기준선 */}
|
||||
<div>
|
||||
<PriceSparkline
|
||||
prices={NEGOTIATION_STEPS.map((step) => step.price)}
|
||||
targetPrice={TARGET_PRICE}
|
||||
progress={activeStep < 0 ? 0 : (activeStep + 1) / NEGOTIATION_STEPS.length}
|
||||
/>
|
||||
<div className="flex justify-between mt-2">
|
||||
<Typography variant="micro">시작가 {START_PRICE.toLocaleString()}</Typography>
|
||||
<Typography variant="micro" className="text-primary">
|
||||
목표가 {TARGET_PRICE.toLocaleString()}
|
||||
</Typography>
|
||||
</div>
|
||||
<Typography variant="caption" className="mt-3">
|
||||
실제 협상 화면을 재구성한 데모입니다.
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="h-10">
|
||||
<AnimatePresence mode="wait">
|
||||
{activeStep !== -1 && NEGOTIATION_STEPS[activeStep]?.badge && (
|
||||
<motion.div
|
||||
key={NEGOTIATION_STEPS[activeStep].badge}
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.95, opacity: 0 }}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-positive-soft text-positive border border-positive/15 text-xs font-bold"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 shrink-0" />
|
||||
{NEGOTIATION_STEPS[activeStep].badge}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 우: 대화 말풍선 (봇 좌 / 파트너 우) */}
|
||||
<div className="md:col-span-7 flex flex-col justify-end space-y-5 h-[340px] md:h-[420px] relative overflow-hidden">
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-surface via-transparent to-transparent h-12 pointer-events-none z-10" />
|
||||
|
||||
<div
|
||||
ref={chatContainerRef}
|
||||
className="flex flex-col gap-5 overflow-y-auto pr-1 scrollbar-none w-full h-full justify-center"
|
||||
>
|
||||
<AnimatePresence mode="wait" initial={false}>
|
||||
{activeStep === -1 ? (
|
||||
<motion.div
|
||||
key="onboarding-guide"
|
||||
initial={{ opacity: 0, y: 15, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -15, scale: 0.97 }}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="flex flex-col items-center justify-center text-center p-8 border border-dashed border-line-strong rounded-[28px] bg-white shadow-[0_4px_20px_rgba(0,0,0,0.01)] max-w-md mx-auto"
|
||||
>
|
||||
<div className="w-12 h-12 rounded-full bg-primary-soft flex items-center justify-center text-primary mb-4">
|
||||
<Bot className="w-6 h-6 animate-pulse" />
|
||||
</div>
|
||||
<h3 className="text-base font-bold text-ink mb-1.5">실시간 AI 협상 대화</h3>
|
||||
<p className="text-xs text-ink-soft font-semibold leading-relaxed break-keep">
|
||||
화면을 스크롤하면 실시간 단가 조율 대화가 시작됩니다.
|
||||
</p>
|
||||
<div className="mt-4 flex items-center gap-1.5 text-[11px] font-bold text-primary animate-bounce">
|
||||
<span>마우스 휠 스크롤하기</span>
|
||||
<span>↓</span>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-5 w-full mt-auto">
|
||||
{NEGOTIATION_STEPS.slice(0, activeStep + 1).map((item, idx) => {
|
||||
const isBot = item.editorNodes[0].sender === "bot"
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={idx}
|
||||
initial={{ opacity: 0, y: 15, scale: 0.97 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -10, scale: 0.97 }}
|
||||
transition={{ duration: 0.4, ease: EASE_OUT_EXPO }}
|
||||
className={`flex flex-col ${isBot ? "items-start" : "items-end"} w-full`}
|
||||
>
|
||||
<div className={`flex items-center gap-1.5 mb-1 text-[11px] font-bold text-ink-muted ${isBot ? "" : "flex-row-reverse"}`}>
|
||||
<span className={`flex items-center gap-1 ${isBot ? "text-primary" : "text-ink-soft"}`}>
|
||||
{isBot ? (
|
||||
<>
|
||||
<Bot className="w-3.5 h-3.5" />
|
||||
<span>NEGOTIUM BOT</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Handshake className="w-3.5 h-3.5" />
|
||||
<span>PARTNER</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`max-w-[85%] rounded-[20px] p-4 text-sm leading-relaxed font-semibold shadow-[0_2px_8px_rgba(0,0,0,0.02)] transition-all duration-300 ${
|
||||
isBot ? "bg-primary-soft text-ink rounded-tl-none" : "bg-white text-ink rounded-tr-none"
|
||||
}`}
|
||||
>
|
||||
<SlateRenderer nodes={item.editorNodes} />
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// 시작가(첫 제시가)·목표가 — 좌측 패널 델타·스파크라인 기준값
|
||||
const START_PRICE = 1200000
|
||||
const TARGET_PRICE = 1080000
|
||||
|
||||
// 데모 대화 시나리오 — 1,200,000원 제시에서 1,050,000원 낙찰까지 6스텝
|
||||
const NEGOTIATION_STEPS: DialogueStep[] = [
|
||||
{
|
||||
step: 1,
|
||||
price: 1200000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'supplier',
|
||||
children: [
|
||||
{ text: '협력사', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '현재 글로벌 원재료 상승 요인으로 제안할 수 있는 최선의 단가는 1,200,000원입니다. 이 이하로는 마진 확보가 어렵습니다.' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 2,
|
||||
price: 1150000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'bot',
|
||||
children: [
|
||||
{ text: 'AI 흥정 봇', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '제시해주신 1,200,000원은 당사 타 유사 품목 이력 및 시중 원가 인덱스 데이터 대비 약 8.3% 높게 책정되어 있습니다. ', italic: true },
|
||||
{ text: '상호 호혜적 장기 계약 체결을 전제로 조율가 범위를 반영해 제안해 드립니다.', code: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 3,
|
||||
price: 1150000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'supplier',
|
||||
children: [
|
||||
{ text: '협력사', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '제조 공정상 급격한 인하는 무리가 있으나, 상생 협력 차원에서 1,150,000원까지는 즉시 조정해 드릴 용의가 있습니다.' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 4,
|
||||
price: 1080000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'bot',
|
||||
children: [
|
||||
{ text: 'AI 흥정 봇', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '적극적인 협조에 감사드립니다. 만약 연간 최소 발주 수량을 보증하고 공급망 일정을 다소 유연화해주신다면, 목표가인 1,080,000원 선까지 맞출 수 있을까요?', italic: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 5,
|
||||
price: 1050000,
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'supplier',
|
||||
children: [
|
||||
{ text: '협력사', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '좋습니다. 제안하신 연간 개런티 확보 및 대금 현금 결제 기한 단축을 승인해 주시는 조건으로, ' },
|
||||
{ text: '최종 조율가 1,050,000원으로 맞춰서 계약을 체결하겠습니다.', bold: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
step: 6,
|
||||
price: 1050000,
|
||||
badge: '낙찰 성공 · 12.5% 예산 절감',
|
||||
editorNodes: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
sender: 'bot',
|
||||
children: [
|
||||
{ text: 'AI 흥정 봇', bold: true },
|
||||
{ text: ' : ' },
|
||||
{ text: '최종 합의 접수 완료 — 가이드 상한가(1,200,000원) 대비 합의 낙찰가 1,050,000원으로 최종 계약 승인 처리 완료되었습니다. ', bold: true },
|
||||
{ text: '본 흥정 마일스톤 및 단가 타결 히스토리는 사내 투명성 보증을 위해 보존 기록됩니다.', code: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,466 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { motion } from "motion/react"
|
||||
import { ArrowRight, RotateCcw } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import {
|
||||
DEMO_ITEMS,
|
||||
MAX_CARDS,
|
||||
respondToOffer,
|
||||
round10,
|
||||
savings,
|
||||
simulateBuyerRun,
|
||||
won,
|
||||
type DemoItem,
|
||||
type Outcome,
|
||||
type Role,
|
||||
type Turn,
|
||||
} from "@/lib/negotiation-sim"
|
||||
|
||||
type Step = "role" | "play"
|
||||
|
||||
/**
|
||||
* 랜딩 인터랙티브 협상 데모.
|
||||
*
|
||||
* 스크롤로 재생만 되던 기존 콘솔을 대체한다. 구경이 아니라 사용자가 한쪽을 맡아
|
||||
* 실제로 값을 제시하고 판정을 받는다 — 광고로 들어온 잠재고객이 제품을 만져보는 자리다.
|
||||
*
|
||||
* 판정 규칙은 lib/negotiation-sim 에 있고 이 파일은 화면만 맡는다.
|
||||
*/
|
||||
export function NegotiationDemo() {
|
||||
const [step, setStep] = useState<Step>("role")
|
||||
const [role, setRole] = useState<Role>("seller")
|
||||
const [item, setItem] = useState<DemoItem>(DEMO_ITEMS[0])
|
||||
const [turns, setTurns] = useState<Turn[]>([])
|
||||
const [cardsUsed, setCardsUsed] = useState(0)
|
||||
const [outcome, setOutcome] = useState<Outcome>("running")
|
||||
const [offer, setOffer] = useState(DEMO_ITEMS[0].listPrice)
|
||||
/* 입력란의 원문. offer 와 따로 두는 이유는 타이핑 도중 상태다 — 숫자 하나로 묶으면
|
||||
"1" 을 치는 순간 범위 밖이라 튕겨서 사용자와 싸우게 된다. 확정은 blur/Enter 에서 한다. */
|
||||
const [offerText, setOfferText] = useState(won(DEMO_ITEMS[0].listPrice))
|
||||
const [finalPrice, setFinalPrice] = useState(DEMO_ITEMS[0].listPrice)
|
||||
|
||||
const logRef = useRef<HTMLDivElement>(null)
|
||||
const timers = useRef<number[]>([])
|
||||
|
||||
// 재생 중인 buyer 시나리오 타이머는 리셋·언마운트 때 반드시 걷어낸다.
|
||||
const clearTimers = () => {
|
||||
timers.current.forEach(clearTimeout)
|
||||
timers.current = []
|
||||
}
|
||||
useEffect(() => clearTimers, [])
|
||||
|
||||
/** 역할 선택 화면으로 완전히 되돌린다. 같은 역할로만 다시 하면 나머지 절반은
|
||||
영영 안 보게 되므로, 다시 해보기는 역할부터 고르게 하는 게 맞다. */
|
||||
const restart = () => {
|
||||
reset()
|
||||
setStep("role")
|
||||
}
|
||||
|
||||
const reset = (nextItem = item, nextRole = role) => {
|
||||
clearTimers()
|
||||
setTurns([])
|
||||
setCardsUsed(0)
|
||||
setOutcome("running")
|
||||
setFinalPrice(nextItem.listPrice)
|
||||
const start = nextRole === "seller" ? nextItem.listPrice : nextItem.marketLow
|
||||
setOffer(start)
|
||||
setOfferText(won(start))
|
||||
}
|
||||
|
||||
const pickRole = (r: Role) => {
|
||||
setRole(r)
|
||||
reset(item, r)
|
||||
setStep("play")
|
||||
}
|
||||
|
||||
const pickItem = (it: DemoItem) => {
|
||||
setItem(it)
|
||||
reset(it, role)
|
||||
}
|
||||
|
||||
// 새 말풍선이 붙으면 기록을 바닥으로 붙인다.
|
||||
useEffect(() => {
|
||||
logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" })
|
||||
}, [turns])
|
||||
|
||||
/** seller — 사용자가 공급사가 되어 값을 제시하고 에이전트가 응수한다. */
|
||||
const submitOffer = () => {
|
||||
if (outcome !== "running") return
|
||||
const priced = round10(offer)
|
||||
const mine: Turn = { id: turns.length, side: "counterpart", text: `${won(priced)}원까지는 맞춰드릴 수 있습니다.`, price: priced }
|
||||
setTurns((prev) => [...prev, mine])
|
||||
|
||||
const res = respondToOffer(item, priced, cardsUsed)
|
||||
const id = window.setTimeout(() => {
|
||||
setTurns((prev) => [...prev, { id: prev.length, side: "agent", text: res.text, price: res.price }])
|
||||
setFinalPrice(res.outcome === "award" ? priced : res.price)
|
||||
setOutcome(res.outcome)
|
||||
if (res.outcome === "running") {
|
||||
setCardsUsed((c) => c + 1)
|
||||
// 에이전트가 부른 값에서 다시 시작. 입력란도 같이 갱신해야 슬라이더와 숫자가 어긋나지 않는다.
|
||||
setOffer(res.price)
|
||||
setOfferText(won(res.price))
|
||||
}
|
||||
}, 620)
|
||||
timers.current.push(id)
|
||||
}
|
||||
|
||||
/** buyer — 목표가만 정하면 에이전트가 알아서 붙는 걸 지켜본다. */
|
||||
const runBuyer = () => {
|
||||
if (turns.length > 0) return
|
||||
const target = round10(offer)
|
||||
const run = simulateBuyerRun(item, target)
|
||||
run.turns.forEach((turn, i) => {
|
||||
const id = window.setTimeout(() => {
|
||||
setTurns((prev) => [...prev, turn])
|
||||
if (turn.price) setFinalPrice(turn.price)
|
||||
if (i === run.turns.length - 1) setOutcome(run.outcome)
|
||||
}, 500 + i * 900)
|
||||
timers.current.push(id)
|
||||
})
|
||||
}
|
||||
|
||||
const done = outcome !== "running"
|
||||
const { amount, rate } = savings(item, finalPrice)
|
||||
const sliderMin = role === "seller" ? round10(item.anchor * 0.94) : round10(item.anchor * 0.94)
|
||||
const sliderMax = role === "seller" ? item.listPrice : item.marketLow
|
||||
|
||||
/* 협상이 시작된 뒤 구매자는 목표가를 못 바꾼다 — 목표가를 정하고 위임하는 게 제품의 전제다.
|
||||
공급사는 카드가 남아 있는 한 계속 제시할 수 있다. */
|
||||
const inputLocked = role === "buyer" && turns.length > 0
|
||||
|
||||
/* 추천가는 시뮬레이터가 실제로 쓰는 수치에서 가져온다. 지어낸 숫자를 추천이라 부르면
|
||||
사용자가 그대로 넣었을 때 결과가 설명되지 않는다. */
|
||||
const recommended = role === "seller" ? item.marketLow : item.anchor
|
||||
const recommendReason =
|
||||
role === "seller"
|
||||
? `같은 사양 시장 최저가 선입니다. 여기서부터 에이전트가 근거를 들고 응수합니다.`
|
||||
: `결렬 없이 도달 가능한 최저선입니다. 더 낮추면 협상이 성사되지 않습니다.`
|
||||
|
||||
/** 슬라이더·직접입력·추천적용이 모두 거쳐가는 단일 확정 경로. 범위로 당기고 10원 단위로 맞춘다. */
|
||||
const commitOffer = (raw: number) => {
|
||||
if (inputLocked) return
|
||||
const next = Number.isFinite(raw) && raw > 0 ? round10(Math.min(sliderMax, Math.max(sliderMin, raw))) : offer
|
||||
setOffer(next)
|
||||
/* 확정된 값은 콤마를 넣어 보여준다 — 화면의 다른 금액이 전부 won() 이라
|
||||
여기만 1018800 으로 나오면 같은 값으로 안 읽힌다. 타이핑 중에는 숫자만 남긴다. */
|
||||
setOfferText(won(next))
|
||||
}
|
||||
|
||||
return (
|
||||
<Section id="how-it-works" bg="stage" width="lg">
|
||||
{/* 머리는 손으로 짜지 않고 SectionHeading 을 쓴다. 예전엔 여기서 직접 조판하느라
|
||||
아이브로우 간격만 20px(다른 섹션은 12px)이었다 — 프리미티브를 우회하면
|
||||
같은 관계에 두 번째 값이 생긴다. */}
|
||||
{/* 두 문장은 의미 단위가 다르므로 줄을 명시적으로 나눈다.
|
||||
자동 줄바꿈에 맡기면 어절이 어색하게 끊긴다.
|
||||
|
||||
예전 카피는 "에이전트는 정해진 기준을 벗어나지 않습니다" 였다. FAQ 2번
|
||||
("에이전트가 우리 기준을 벗어나 합의해 버리면요?")을 헤드라인으로 끌어올린
|
||||
것이었는데, 아직 생기지도 않은 반론에 가장 비싼 한 줄을 쓰고 있었다.
|
||||
게다가 부정문이라 안 하는 일을 약속했다 — 체험을 권하는 자리에는 맞지 않는다.
|
||||
방어는 FAQ 에 그대로 남아 있으니 여기서는 능력을 말한다. */}
|
||||
<SectionHeading
|
||||
align="center"
|
||||
tone="stage"
|
||||
eyebrow="Try it Yourself"
|
||||
title={
|
||||
<>
|
||||
<span className="text-white">사용할수록 진화하는 에이전틱 협상,</span>
|
||||
<br />
|
||||
<span className="text-on-stage-soft/60">직접 경험해 보세요!</span>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* AnimatePresence mode="wait" 를 쓰지 않는다. 나가는 애니메이션이 끝나야 다음
|
||||
화면이 마운트돼서 클릭 후 0.8초가 빈다 — 역할 선택처럼 즉시 반응해야 하는
|
||||
전환에는 맞지 않는 도구다. 나가는 연출 없이 바로 갈아끼우고 짧게 들어온다. */}
|
||||
{step === "role" ? (
|
||||
<motion.div
|
||||
key="role"
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.28, ease: EASE_OUT_EXPO }}
|
||||
className="grid grid-cols-1 sm:grid-cols-2 gap-4"
|
||||
>
|
||||
<RoleCard
|
||||
title="공급사로 해보기"
|
||||
lead="직접 단가를 제시하면 에이전트가 응수합니다."
|
||||
detail="협상 카드 3장 안에서 단가가 어디까지 조율되는지 확인하실 수 있습니다."
|
||||
onClick={() => pickRole("seller")}
|
||||
/>
|
||||
<RoleCard
|
||||
title="구매 담당자로 해보기"
|
||||
lead="목표가만 정하면 에이전트가 협력사와 조율합니다."
|
||||
detail="기준을 벗어난 목표가를 설정했을 때의 처리 방식도 함께 확인하실 수 있습니다."
|
||||
onClick={() => pickRole("buyer")}
|
||||
/>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="play"
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.28, ease: EASE_OUT_EXPO }}
|
||||
/* 유리 패널로 띄운다. 컨트롤과 대화 로그가 섹션 배경 위에 그냥 얹혀 있으면
|
||||
무대와 같은 색이라 경계가 없고, 조작할 수 있는 영역인지 읽히지 않는다.
|
||||
재질은 무대 위 2차 CTA 와 같다 — 옅은 흰 채움 + backdrop-blur + 위쪽
|
||||
안쪽 하이라이트 + 아래로 깔리는 그림자. 화면 안에 재질이 두 종류면 따로 논다.
|
||||
테두리는 white/12 로 얕게 둔다. 이건 조작 요소가 아니라 면이라 버튼만큼
|
||||
세울 필요가 없고, 세우면 오히려 카드가 버튼처럼 보인다. */
|
||||
className={
|
||||
"rounded-card border border-white/12 bg-white/[0.06] " +
|
||||
"backdrop-blur-xl backdrop-saturate-150 " +
|
||||
"shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),0_24px_60px_-24px_rgba(3,6,15,0.9)] " +
|
||||
"p-6 sm:p-8 lg:p-10"
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">
|
||||
{/* 좌 — 품목·컨트롤·현재가 */}
|
||||
<div className="lg:col-span-5 space-y-8">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{DEMO_ITEMS.map((it) => (
|
||||
<button
|
||||
key={it.id}
|
||||
type="button"
|
||||
onClick={() => pickItem(it)}
|
||||
className={`px-4 py-2 rounded-full text-[13px] font-semibold transition-colors ${
|
||||
it.id === item.id
|
||||
? "bg-white text-stage"
|
||||
: "bg-white/5 text-on-stage-soft/75 hover:bg-white/10 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{it.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-[13px] text-on-stage-soft/55 mb-2">{item.spec}</div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-[24px] font-medium text-on-stage-soft/55">₩</span>
|
||||
<span className="text-[52px] md:text-[64px] font-extrabold tracking-[-0.045em] leading-none tabular-nums">
|
||||
{won(finalPrice)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-7 mt-2">
|
||||
{amount > 0 && (
|
||||
<span className="text-[15px] font-semibold text-counter">
|
||||
▼ {won(amount)}원 · {rate.toFixed(1)}%
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!done && (
|
||||
<div className="space-y-4">
|
||||
{/* 에이전트 추천가. 값을 지어내지 않고 시뮬레이터가 실제로 쓰는 수치를 쓴다 —
|
||||
구매자는 anchor(결렬 없이 닿는 최저선, reachable = target >= anchor),
|
||||
공급사는 marketLow(에이전트가 응수할 때 인용하는 값). 추천만 하고
|
||||
확정은 사용자가 한다. 그게 이 데모가 보여줘야 할 관계다. */}
|
||||
<div className="flex items-center justify-between gap-3 rounded-control border border-primary-on-stage/25 bg-primary-on-stage/10 px-4 py-3">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[12px] font-semibold text-primary-on-stage mb-0.5">에이전트 추천</div>
|
||||
<div className="text-[13px] text-on-stage-soft/75 break-keep">{recommendReason}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => commitOffer(recommended)}
|
||||
disabled={inputLocked}
|
||||
className="shrink-0 rounded-control bg-primary-on-stage/20 hover:bg-primary-on-stage/30 px-3 py-2 text-[13px] font-bold tabular-nums text-white transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
{won(recommended)}원 적용
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-baseline justify-between">
|
||||
<label htmlFor="nego-offer" className="text-[14px] font-medium text-on-stage-soft/85">
|
||||
{role === "seller" ? "제시 단가" : "목표 단가"}
|
||||
</label>
|
||||
{/* 직접 입력. 슬라이더만 두면 정확한 값을 못 넣는다 — 실제 구매 담당자는
|
||||
"얼마까지"라는 숫자를 이미 들고 온다. 타이핑 중에는 clamp 하지 않고
|
||||
blur/Enter 에서 확정한다. 입력 즉시 범위로 당기면 손가락과 싸운다. */}
|
||||
<div className="flex items-baseline gap-1">
|
||||
<input
|
||||
id="nego-offer-text"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
aria-label={role === "seller" ? "제시 단가 직접 입력" : "목표 단가 직접 입력"}
|
||||
value={offerText}
|
||||
onChange={(e) => setOfferText(e.target.value.replace(/[^\d]/g, ""))}
|
||||
onBlur={() => commitOffer(Number(offerText.replace(/[^\d]/g, "")))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
commitOffer(Number(offerText.replace(/[^\d]/g, "")))
|
||||
}
|
||||
}}
|
||||
disabled={inputLocked}
|
||||
className="w-32 bg-transparent border-0 border-b-2 border-stage-line focus:border-primary-on-stage hover:border-on-stage-muted rounded-none px-0 py-1 text-right text-[18px] font-bold tabular-nums text-white outline-none transition-colors disabled:opacity-40"
|
||||
/>
|
||||
<span className="text-[15px] font-semibold text-on-stage-soft/70">원</span>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
id="nego-offer"
|
||||
type="range"
|
||||
aria-label={role === "seller" ? "제시 단가 조절" : "목표 단가 조절"}
|
||||
min={sliderMin}
|
||||
max={sliderMax}
|
||||
step={10_000}
|
||||
value={Math.min(sliderMax, Math.max(sliderMin, offer))}
|
||||
onChange={(e) => commitOffer(Number(e.target.value))}
|
||||
disabled={inputLocked}
|
||||
className="w-full accent-primary disabled:opacity-40"
|
||||
/>
|
||||
<div className="flex justify-between text-[12px] text-on-stage-soft/45">
|
||||
<span>{won(sliderMin)}</span>
|
||||
<span>{won(sliderMax)}</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="stage"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
onClick={role === "seller" ? submitOffer : runBuyer}
|
||||
disabled={inputLocked}
|
||||
>
|
||||
{role === "seller" ? "이 값으로 제시하기" : "협상 시작"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{role === "seller" && (
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-[13px] text-on-stage-soft/55">협상 카드</span>
|
||||
<div className="flex gap-1.5">
|
||||
{Array.from({ length: MAX_CARDS }, (_, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className={`w-7 h-1.5 rounded-full ${i < MAX_CARDS - cardsUsed ? "bg-primary-on-stage" : "bg-white/15"}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 우 — 협상 기록 */}
|
||||
<div className="lg:col-span-7">
|
||||
<div
|
||||
ref={logRef}
|
||||
className="h-[360px] md:h-[440px] overflow-y-auto scrollbar-none flex flex-col gap-4 pr-1"
|
||||
>
|
||||
{turns.length === 0 && (
|
||||
<div className="m-auto text-center text-[15px] text-on-stage-soft/45 max-w-xs break-keep">
|
||||
{role === "seller"
|
||||
? "단가를 정해 제시하면 에이전트가 근거와 함께 응수합니다."
|
||||
: "목표가를 정하고 협상을 시작하면 턴마다 재생됩니다."}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{turns.map((turn) => (
|
||||
<motion.div
|
||||
key={turn.id}
|
||||
initial={{ opacity: 0, y: 14 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.35, ease: EASE_OUT_EXPO }}
|
||||
className={`flex flex-col ${turn.side === "agent" ? "items-start" : "items-end"}`}
|
||||
>
|
||||
<span
|
||||
className={`text-[12px] font-semibold mb-1.5 ${
|
||||
turn.side === "agent" ? "text-primary-on-stage" : "text-counter"
|
||||
}`}
|
||||
>
|
||||
{turn.side === "agent" ? "협상 에이전트" : role === "seller" ? "나 (협력사)" : "협력사"}
|
||||
</span>
|
||||
<div
|
||||
className={`max-w-[88%] rounded-card px-5 py-4 text-[15px] leading-[1.6] break-keep ${
|
||||
turn.side === "agent"
|
||||
? "bg-primary text-white"
|
||||
: "bg-counter-surface text-counter border border-counter/20"
|
||||
}`}
|
||||
>
|
||||
{turn.text}
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{done && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4, ease: EASE_OUT_EXPO }}
|
||||
className="mt-6 border-t border-stage-line pt-6"
|
||||
>
|
||||
<Typography variant="cardTitle" className="text-white mb-1.5">
|
||||
{outcome === "award"
|
||||
? `낙찰 · ${won(amount)}원 절감`
|
||||
: "개찰 — 낙찰자 미정으로 마감했습니다"}
|
||||
</Typography>
|
||||
<p className="text-[15px] text-on-stage-soft/70 leading-[1.6] break-keep mb-6">
|
||||
{outcome === "award"
|
||||
? `최초 제시가 ${won(item.listPrice)}원에서 ${rate.toFixed(1)}% 내려왔습니다. 실제 운영에서는 협력사 수만큼 이 협상이 동시에 진행됩니다.`
|
||||
: "기준을 벗어나는 값은 억지로 맞추지 않고 담당자에게 넘깁니다. 결렬이 아니라 사람이 판단할 자리를 남기는 것입니다."}
|
||||
</p>
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<Button href="#contact-section" variant="stage" size="lg" className="group">
|
||||
<span>우리 품목으로 상담받기</span>
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</Button>
|
||||
<Button type="button" variant="stageGhost" size="lg" onClick={restart}>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
<span>역할 바꿔서 다시</span>
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<p className="mt-12 text-center text-[13px] text-on-stage-soft/40">
|
||||
실제 판정 규칙(앵커링가·협상 카드 3장·개찰)을 그대로 옮긴 데모입니다. 금액은 예시입니다.
|
||||
</p>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
function RoleCard({
|
||||
title,
|
||||
lead,
|
||||
detail,
|
||||
onClick,
|
||||
}: {
|
||||
title: string
|
||||
lead: string
|
||||
detail: string
|
||||
onClick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="group text-left rounded-card border border-stage-line bg-white/[0.03] hover:bg-white/[0.07] hover:border-white/25 transition-colors p-8 md:p-10"
|
||||
>
|
||||
<Typography variant="heading" as="h3" className="text-white mb-3">
|
||||
{title}
|
||||
</Typography>
|
||||
<p className="text-[16px] text-on-stage-soft/85 leading-[1.6] break-keep mb-2">{lead}</p>
|
||||
<p className="text-[14px] text-on-stage-soft/55 leading-[1.6] break-keep">{detail}</p>
|
||||
<span className="mt-6 inline-flex items-center gap-1.5 text-[16px] font-semibold text-primary-on-stage">
|
||||
시작하기
|
||||
<ArrowRight className="w-4 h-4 transition-transform group-hover:translate-x-0.5" />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -2,8 +2,9 @@ import { motion } from "motion/react"
|
||||
import { GitMerge, RefreshCw, Scale, type LucideIcon } from "lucide-react"
|
||||
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { HEADING_GAP, SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { OrbitRing } from "@/components/ui/orbit-ring"
|
||||
import { useFadeUp } from "@/lib/motion"
|
||||
|
||||
/** 강화학습 섹션 — 협상할수록 좋아진다는 3개 필러 카드. */
|
||||
@@ -11,22 +12,40 @@ export function Reinforcement() {
|
||||
const fadeUp = useFadeUp()
|
||||
|
||||
return (
|
||||
<Section id="reinforcement" bg="surface" bordered className="border-b border-line">
|
||||
<motion.div {...fadeUp} className="mb-20">
|
||||
<SectionHeading
|
||||
className="text-center md:text-left"
|
||||
eyebrow="REINFORCEMENT LEARNING"
|
||||
title="협상할수록, 더 좋은 조건으로"
|
||||
description={
|
||||
<>
|
||||
잘 깎는 노하우는 담당자 머릿속에만 남고, 성과는 그날의 감정과 컨디션에 흔들립니다. negotium은 진행된 모든 거래
|
||||
데이터와 파트너 거절 피드백을 <span className="font-bold text-primary">강화학습 기술</span>에 투입합니다.
|
||||
무턱대고 가격을 후려쳐 상대방의 반발만 사고 결렬로 치닫는 경직된 협상이 아니라, 파트너사가 충분히 받아들일 수
|
||||
있는 범위 내에서 최선의 마진율을 뽑아내도록 조율 페이스를 학습합니다.
|
||||
</>
|
||||
}
|
||||
descriptionClassName="mt-8 max-w-3xl"
|
||||
/>
|
||||
<Section id="reinforcement" bg="stage" width="lg">
|
||||
{/* 순환 링은 원래 히어로에 있었는데, 루프가 의미상 속하는 자리는 여기다 —
|
||||
"협상할수록 좋아진다"를 말하는 섹션이고, 히어로는 이미 세로 예산이 포화였다. */}
|
||||
{/* 머리가 그리드 셀 안에 들어가 있어서 여기만 gap="none" 이다. 그리드 아이템은
|
||||
독립 서식 문맥이라 마진이 상쇄되지 않고, 머리에 mb 를 걸면 items-center 의
|
||||
세로 정렬을 밀어버린다. 섹션 간격은 그리드 래퍼가 대신 진다. */}
|
||||
<motion.div {...fadeUp} className={`grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-center ${HEADING_GAP}`}>
|
||||
<div className="lg:col-span-7">
|
||||
<SectionHeading
|
||||
className="text-center lg:text-left"
|
||||
gap="none"
|
||||
tone="stage"
|
||||
eyebrow="Reinforcement Learning"
|
||||
/* 쉼표에서 줄을 명시적으로 끊는다. break-keep + text-balance 에 맡기면
|
||||
두 줄 길이를 맞추려고 "협상할수록, 더 / 좋은 조건으로" 처럼 쉼표를
|
||||
넘어가서 끊어진다 — 조건절과 결과절이 한 줄에 섞여 의미가 흐려진다. */
|
||||
title={
|
||||
<>
|
||||
협상할수록,
|
||||
<br />더 좋은 조건으로
|
||||
</>
|
||||
}
|
||||
description={
|
||||
<>
|
||||
잘 깎는 요령은 담당자 머릿속에만 남고, 결과는 그날 컨디션에 흔들립니다. 네고시움은 지난 거래 기록과
|
||||
협력사가 거절한 지점을 <span className="font-semibold text-on-stage">강화학습</span>에 넣습니다. 어디까지가
|
||||
받아들여지는 선인지를 데이터로 익혀서, 결렬 없이 도달 가능한 최선을 찾아갑니다.
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="lg:col-span-5 flex justify-center">
|
||||
<OrbitRing className="w-[280px] md:w-[340px] h-auto" />
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
@@ -44,15 +63,15 @@ function PillarCard({ pillar, delay }: { pillar: Pillar; delay: number }) {
|
||||
const fadeUp = useFadeUp(delay)
|
||||
|
||||
return (
|
||||
<motion.div {...fadeUp} className="bg-white p-8 rounded-[28px] flex flex-col justify-between h-[240px]">
|
||||
<div className="w-12 h-12 rounded-2xl bg-primary/5 text-primary flex items-center justify-center">
|
||||
<pillar.icon className="w-6 h-6" />
|
||||
<motion.div {...fadeUp} className="bg-stage-raised border border-stage-line p-8 rounded-card flex flex-col justify-between h-[240px]">
|
||||
<div className="w-11 h-11 rounded-control bg-primary/15 text-on-stage flex items-center justify-center">
|
||||
<pillar.icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<Typography variant="cardTitle" className="mb-2">
|
||||
<Typography variant="cardTitle" className="mb-2 text-on-stage">
|
||||
{pillar.title}
|
||||
</Typography>
|
||||
<Typography variant="caption" className="text-ink-soft">
|
||||
<Typography variant="caption" className="text-on-stage-soft">
|
||||
{pillar.description}
|
||||
</Typography>
|
||||
</div>
|
||||
@@ -68,12 +87,12 @@ const PILLARS: Pillar[] = [
|
||||
},
|
||||
{
|
||||
icon: RefreshCw,
|
||||
title: "지속적인 전략 최적화",
|
||||
description: "전략 강화 학습을 통해 기준선이 상승하고, 점진적으로 개선됩니다. 시간이 곧 협상력이 됩니다.",
|
||||
title: "쓸수록 올라가는 기준선",
|
||||
description: "협상이 쌓일수록 기준선이 올라갑니다. 운영 기간이 그대로 협상력이 됩니다.",
|
||||
},
|
||||
{
|
||||
icon: GitMerge,
|
||||
title: "낙찰 성사율 극대화",
|
||||
description: "무리하게 후려쳐 관계를 깨는 대신, 성사되는 선에서 최대한 끌어냅니다.",
|
||||
title: "결렬 없는 합의",
|
||||
description: "성사되지 않을 선까지 밀지 않습니다. 합의 가능한 범위 안에서 최선을 찾습니다.",
|
||||
},
|
||||
]
|
||||
@@ -1,158 +0,0 @@
|
||||
import { useState } from "react"
|
||||
import { ArrowRight, Clock, ShieldCheck } from "lucide-react"
|
||||
|
||||
import { RangeSlider } from "@/components/ui/range-slider"
|
||||
import { Section } from "@/components/ui/section"
|
||||
import { SectionHeading } from "@/components/ui/section-heading"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
|
||||
/** 도입 ROI 시뮬레이터 — 예산·협력사 수 슬라이더로 예상 절감액을 즉시 계산. */
|
||||
export function ROISimulator() {
|
||||
// 연간 총 구매 예산(억 원)
|
||||
const [budget, setBudget] = useState(50)
|
||||
// 관리 중인 협력사 수
|
||||
const [suppliers, setSuppliers] = useState(50)
|
||||
|
||||
// 보수적 절감율 2.8%~4.5% — 협력사가 많을수록 병렬 대안이 늘어 상향
|
||||
const savingRate = Math.min(0.045, 0.028 + (suppliers / 300) * 0.015)
|
||||
const estimatedSavingsValue = budget * savingRate
|
||||
|
||||
// 협력사당 왕복 흥정 수작업 절약분을 ~6.5시간으로 잡은 추산
|
||||
const savedHours = Math.round(suppliers * 6.5)
|
||||
|
||||
return (
|
||||
<Section id="benchmarks" width="lg" bordered className="border-b border-line">
|
||||
<SectionHeading
|
||||
align="center"
|
||||
className="mb-24"
|
||||
eyebrow="ROI SIMULATION"
|
||||
title={
|
||||
<>
|
||||
negotium 도입 시 <br />
|
||||
예상 절감액 확인하기
|
||||
</>
|
||||
}
|
||||
description={
|
||||
<>
|
||||
아직 실제 도입 실증 사례가 없는 신규 카테고리여도 신뢰할 수 있습니다. <br />
|
||||
연간 구매 예산과 공급사 수만 입력해 보수적인 시뮬레이션 성과를 즉시 시각화해 보세요.
|
||||
</>
|
||||
}
|
||||
descriptionClassName="mt-4 text-[17px] max-w-2xl"
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-12 gap-16 items-start">
|
||||
{/* 좌: 입력 슬라이더 */}
|
||||
<div className="lg:col-span-6 space-y-12">
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-[16px] font-bold text-ink">연간 총 구매 예산</label>
|
||||
<span className="text-lg font-black text-primary font-mono">{formatCurrency(budget)}</span>
|
||||
</div>
|
||||
<Typography variant="caption">원자재, 부자재, 가공비, 운송비 등 협상에 연동할 총 연간 구매 규모입니다.</Typography>
|
||||
<div className="pt-2">
|
||||
<RangeSlider min={5} max={1000} step={5} value={budget} onChange={setBudget} />
|
||||
<div className="flex justify-between text-[11px] text-ink-faint font-bold pt-2">
|
||||
<span>5억 원</span>
|
||||
<span>500억 원</span>
|
||||
<span>1조 원</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-[16px] font-bold text-ink">관리 중인 총 협력사 수</label>
|
||||
<span className="text-lg font-black text-primary font-mono">{suppliers}개사</span>
|
||||
</div>
|
||||
<Typography variant="caption">AI 봇 "밀당"이 동시에 일대일로 자동 조율할 잠재 공급사 수량입니다.</Typography>
|
||||
<div className="pt-2">
|
||||
<RangeSlider min={5} max={300} step={5} value={suppliers} onChange={setSuppliers} />
|
||||
<div className="flex justify-between text-[11px] text-ink-faint font-bold pt-2">
|
||||
<span>5개사</span>
|
||||
<span>150개사</span>
|
||||
<span>300개사</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 bg-surface p-5 rounded-2xl border border-line">
|
||||
<ShieldCheck className="w-5 h-5 text-positive flex-shrink-0 mt-0.5" />
|
||||
<Typography variant="caption" className="text-ink-soft">
|
||||
본 시뮬레이션은 글로벌 최저가 스캔(LPS) 시장 표준 및 다수 B2B 자율 협상 데이터의 보수적인 평균 수치(3.1% ~ 4.2%
|
||||
절감)를 적용하여 산정되었습니다. 실사 수준의 검증은 파일 연동을 통해 무상 지원됩니다.
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 우: 결과 지표 */}
|
||||
<div className="lg:col-span-6 lg:pl-10 space-y-12">
|
||||
<div className="space-y-3">
|
||||
<Typography variant="micro" className="text-primary block">
|
||||
ESTIMATED ANNUAL SAVINGS
|
||||
</Typography>
|
||||
<h3 className="text-sm font-semibold text-ink-muted">매년 절감 가능한 구매 원가 (보수적 추산)</h3>
|
||||
<div className="text-3xl sm:text-[44px] font-black text-primary font-mono tracking-tight leading-tight pt-1">
|
||||
{formatSavings(estimatedSavingsValue)}
|
||||
</div>
|
||||
<Typography variant="caption" className="text-ink-soft font-medium pt-1">
|
||||
사각지대에 방치되던 꼬리 거래(Tail Spend)의 상시 병렬 협상 및 인터넷 실시간 앵커가 시세 연동을 통해, 기존 수동
|
||||
흥정으로 놓치고 있던 원가 이탈을 완벽히 방어해냅니다.
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-line pt-8 space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Clock className="w-5 h-5 text-ink-muted" />
|
||||
<span className="text-xs font-bold text-ink-soft">
|
||||
연간 실무 단축 시간: <b className="text-ink font-mono text-sm ml-1">{savedHours.toLocaleString()}시간</b>
|
||||
</span>
|
||||
</div>
|
||||
<Typography variant="caption">
|
||||
메일 전송, 유선 흥정, 엑셀 취합 등에 낭비되던 소모적인 절차가 실시간 링크 전송과 AI 봇의 24시간 자율 대응으로
|
||||
완전히 생략되어 고부가가치 전략 구매 기획에 전념할 수 있습니다.
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-line pt-8 flex items-center justify-between">
|
||||
<div>
|
||||
<h4 className="text-xs font-bold text-ink">예상 도입 ROI 회수 기간</h4>
|
||||
<p className="text-[11px] text-ink-muted font-semibold mt-1">도입 즉시 마진 확보 개시</p>
|
||||
</div>
|
||||
<a
|
||||
href="#contact-section"
|
||||
className="inline-flex items-center gap-2 text-xs font-bold text-primary hover:gap-3 transition-all"
|
||||
>
|
||||
<span>무상 맞춤 검증 신청하기</span>
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 억 원 단위 → "50억 원" / "1조 200억 원" 표기 */
|
||||
function formatCurrency(val: number) {
|
||||
if (val >= 100) {
|
||||
const b = Math.floor(val / 100)
|
||||
const m = val % 100
|
||||
return m > 0 ? `${b}조 ${m}00억 원` : `${b}조 원`
|
||||
}
|
||||
return `${val}억 원`
|
||||
}
|
||||
|
||||
/** 억 원 단위 → "1억 5,500만 원" 표기 */
|
||||
function formatSavings(val: number) {
|
||||
const rawWon = val * 100000000
|
||||
if (rawWon >= 100000000) {
|
||||
const eonPart = Math.floor(rawWon / 100000000)
|
||||
const manPart = Math.floor((rawWon % 100000000) / 10000)
|
||||
if (manPart > 0) {
|
||||
return `${eonPart}억 ${manPart.toLocaleString()}만 원`
|
||||
}
|
||||
return `${eonPart}억 원`
|
||||
}
|
||||
return `${Math.floor(rawWon / 10000).toLocaleString()}만 원`
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import { cn } from "@/lib/utils"
|
||||
// CTA 버튼 토큰. 랜딩의 CTA 는 전부 앵커 스크롤이라 href 를 주면 <a> 로 렌더한다
|
||||
// (SSG 특성상 하이드레이션 전에도 동작).
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 transition-all cursor-pointer disabled:opacity-50",
|
||||
/* transition-colors 로 좁힌다. transition-all 이면 헤더 CTA 가 무대↔라이트로 variant 를
|
||||
통째로 바꿀 때 배경이 투명에서 차오르며 플리커로 읽힌다. */
|
||||
"inline-flex items-center justify-center gap-2 transition-colors duration-200 cursor-pointer disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
@@ -14,13 +16,40 @@ const buttonVariants = cva(
|
||||
secondary: "bg-fill hover:bg-fill-hover text-ink-soft hover:text-ink",
|
||||
// 밝은 배경 위 반투명 보조 버튼 (글라스 히어로)
|
||||
glass: "bg-white/70 hover:bg-white text-ink-soft hover:text-ink border border-white shadow-sm",
|
||||
// 다크 무대 위 1차 CTA
|
||||
stage: "bg-primary hover:bg-primary-deep text-white",
|
||||
/* 다크 무대 위 2차 CTA — 흰 알약.
|
||||
테두리를 stage-line(#1E2A52)으로 두면 안 된다. 그 색은 무대 바닥(#070E24) 위
|
||||
카드용이라, 방사형 광원부(#16205A)에 앉는 GNB 자리에서는 배경과 대비가 1.09:1 로
|
||||
사라진다. 채움도 없으면 남는 건 흰 글자뿐이라 옆 nav 링크와 구분되지 않는다.
|
||||
그래서 무대색 토큰이 아니라 흰색 알파로 잡는다 — 무대 어디에 놓여도 같이 성립한다.
|
||||
옅은 채움이 테두리보다 "누를 수 있는 것"을 더 강하게 전달하므로 둘 다 준다. */
|
||||
/* 유리(glassmorphism). 배경 영상이 비쳐 보이되 글자는 읽히는 상태를 만든다.
|
||||
구성은 넷이다 — 옅은 흰 채움, 뒤를 흐리는 backdrop-blur, 위쪽 1px 안쪽 하이라이트
|
||||
(유리 모서리에 빛이 걸리는 부분), 아래로 깔리는 부드러운 그림자(떠 있는 느낌).
|
||||
채도를 살짝 올리면(saturate) 뒤가 흐려지며 빠지는 색기가 돌아온다.
|
||||
|
||||
테두리는 white/40 에서 더 못 내린다. /30 으로 낮추면 무대 광원부(#16205A) 대비가
|
||||
2.60:1 로 떨어져 WCAG 1.4.11(UI 경계 3:1)에 미달한다 — 유리 느낌 때문에 버튼이
|
||||
안 보이던 원래 문제로 돌아간다. 투명감은 채움과 blur 로 내고 테두리는 지킨다.
|
||||
|
||||
hover 는 흰색 반전이 아니라 채움을 밝힌다. 유리는 뒤가 비치는 게 정체성이라
|
||||
불투명하게 뒤집으면 그 순간 유리가 아니게 된다. */
|
||||
stageGhost:
|
||||
"bg-white/12 hover:bg-white/25 text-white border border-white/40 hover:border-white/60 " +
|
||||
"backdrop-blur-md backdrop-saturate-150 " +
|
||||
"shadow-[inset_0_1px_0_0_rgba(255,255,255,0.30),0_8px_24px_-10px_rgba(3,6,15,0.7)]",
|
||||
},
|
||||
// radius 는 사이즈 무관 rounded-2xl(16px) 로 통일 — 알약형 금지
|
||||
/* 레퍼런스(statworx) 실측: 10.4px / 600 / 알약(radius 39px) / 패딩 12·24 / 높이 33px.
|
||||
작고 조밀한 버튼이 확신 있어 보인다 — 크고 굵은 버튼은 설득이 아니라 호소로 읽힌다.
|
||||
한글 보정: 10.4px 는 판독이 어려워 12~13px 로 올리고 높이도 터치 타깃까지 확보한다.
|
||||
(기존 주석의 "알약형 금지" 규칙은 레퍼런스 채택으로 폐기했다.) */
|
||||
size: {
|
||||
pill: "px-4.5 py-2.5 text-sm font-semibold rounded-2xl",
|
||||
md: "px-6 py-2.5 text-xs font-bold rounded-2xl",
|
||||
lg: "px-8 py-4.5 text-base font-bold rounded-2xl",
|
||||
xl: "px-10 py-5 text-base font-bold rounded-2xl",
|
||||
pill: "px-5 py-2.5 text-[12px] font-semibold rounded-full",
|
||||
md: "px-6 py-3 text-[12px] font-semibold rounded-full",
|
||||
lg: "px-7 py-3.5 text-[13px] font-semibold rounded-full",
|
||||
xl: "px-8 py-4 text-[14px] font-semibold rounded-full",
|
||||
stageRound: "px-7 py-3.5 text-[13px] font-semibold rounded-full",
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: "primary", size: "lg" },
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { useEffect, useId, useRef, useState } from "react"
|
||||
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
|
||||
import { Check, Loader2, X } from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
import { isEmailLike, submitLead } from "@/lib/lead"
|
||||
|
||||
/*
|
||||
* 데모 요청 모달 — 이름·이메일만 받는 리드 캡처.
|
||||
*
|
||||
* 상담 신청(contact.tsx)은 회사명·담당자·연락처·문의내용까지 받는 고관여 폼이다.
|
||||
* 이건 그 앞단이다. 필드가 늘수록 이탈이 늘기 때문에 두 칸에서 멈춘다 — 영업이
|
||||
* 첫 연락을 하는 데 필요한 최소가 이름과 이메일이고, 나머지는 통화에서 채운다.
|
||||
*
|
||||
* 전체 페이지로 보내지 않고 모달로 띄우는 이유도 같다. 히어로에서 관심이 생긴
|
||||
* 순간에 그 자리에서 받아야 한다. 스크롤로 내려보내면 그 사이에 식는다.
|
||||
*/
|
||||
export function DemoRequestModal({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const [name, setName] = useState("")
|
||||
const [email, setEmail] = useState("")
|
||||
const [website, setWebsite] = useState("") // 봇 함정
|
||||
const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle")
|
||||
const dialogRef = useRef<HTMLDivElement>(null)
|
||||
const firstFieldRef = useRef<HTMLInputElement>(null)
|
||||
const restoreFocusTo = useRef<HTMLElement | null>(null)
|
||||
const reduce = useReducedMotion()
|
||||
const titleId = useId()
|
||||
|
||||
/* 열릴 때마다 초기화. 남겨두면 성공 화면이 다시 뜨거나 이전 에러가 붙어 나온다. */
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setStatus("idle")
|
||||
restoreFocusTo.current = document.activeElement as HTMLElement | null
|
||||
const t = setTimeout(() => firstFieldRef.current?.focus(), 60)
|
||||
return () => clearTimeout(t)
|
||||
}, [open])
|
||||
|
||||
/* 배경 스크롤 잠금. 모달 뒤에서 페이지가 움직이면 모달이 페이지의 일부처럼 읽힌다. */
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const prev = document.body.style.overflow
|
||||
document.body.style.overflow = "hidden"
|
||||
return () => {
|
||||
document.body.style.overflow = prev
|
||||
restoreFocusTo.current?.focus?.()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
/* Esc 로 닫기 + Tab 을 모달 안에 가둔다. 가두지 않으면 뒤 페이지의 링크로 포커스가
|
||||
빠져나가고, 키보드·스크린리더 사용자는 자기가 어디 있는지 알 수 없게 된다. */
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
if (e.key !== "Tab") return
|
||||
const focusables = dialogRef.current?.querySelectorAll<HTMLElement>(
|
||||
'button:not([disabled]), input:not([disabled]), a[href]',
|
||||
)
|
||||
if (!focusables?.length) return
|
||||
const first = focusables[0]
|
||||
const last = focusables[focusables.length - 1]
|
||||
if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault()
|
||||
last.focus()
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", onKeyDown)
|
||||
return () => document.removeEventListener("keydown", onKeyDown)
|
||||
}, [open, onClose])
|
||||
|
||||
const valid = name.trim().length > 0 && isEmailLike(email)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!valid || status === "submitting") return
|
||||
setStatus("submitting")
|
||||
const result = await submitLead({ source: "demo-request", name, email, website })
|
||||
setStatus(result.ok ? "success" : "error")
|
||||
}
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-6">
|
||||
<motion.div
|
||||
className="absolute inset-0 bg-stage-deep/80 backdrop-blur-sm"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
className="relative w-full max-w-md bg-white rounded-card p-8 sm:p-10 shadow-2xl"
|
||||
initial={reduce ? { opacity: 0 } : { opacity: 0, y: 16, scale: 0.98 }}
|
||||
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }}
|
||||
exit={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.99 }}
|
||||
transition={{ duration: 0.28, ease: EASE_OUT_EXPO }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="닫기"
|
||||
className="absolute top-4 right-4 p-2 text-ink-muted hover:text-ink transition-colors cursor-pointer"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
{status === "success" ? (
|
||||
<div className="text-center py-4">
|
||||
<div className="w-12 h-12 rounded-full bg-positive-soft text-positive flex items-center justify-center mx-auto mb-5">
|
||||
<Check className="w-6 h-6" />
|
||||
</div>
|
||||
<Typography variant="cardTitle" as="h2" id={titleId} className="mb-3">
|
||||
데모 신청이 접수되었습니다
|
||||
</Typography>
|
||||
{/* 폼에서 "Demo를 보내드립니다"라고 약속했으므로 성공 화면도 같은 약속을 지킨다.
|
||||
여기서 "일정을 잡아 연락드립니다"로 새면 방문자가 무엇을 기다려야 하는지 모른다. */}
|
||||
<Typography variant="small">
|
||||
입력하신 이메일로 사용해보실 수 있는 Demo를 보내드립니다.
|
||||
</Typography>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* 제목은 여는 버튼과 같은 말을 쓴다. 버튼이 "받기"인데 여기가 "요청"이면
|
||||
전환 순간에 다른 화면에 온 것처럼 읽힌다. */}
|
||||
<Typography variant="cardTitle" as="h2" id={titleId} className="mb-2">
|
||||
실제 데모 받기
|
||||
</Typography>
|
||||
<Typography variant="small" className="mb-8">
|
||||
성함과 이메일만 남겨주시면, 사용해보실 수 있는 Demo를 보내드립니다!
|
||||
</Typography>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-7">
|
||||
{/* 봇 함정. 화면에서 감추되 display:none 은 쓰지 않는다 — 일부 봇은
|
||||
숨겨진 필드를 걸러낸다. 스크린리더에는 aria-hidden + tabIndex 로 숨긴다. */}
|
||||
<div className="absolute w-px h-px -left-[9999px] overflow-hidden" aria-hidden>
|
||||
<input
|
||||
type="text"
|
||||
name="website"
|
||||
tabIndex={-1}
|
||||
autoComplete="off"
|
||||
value={website}
|
||||
onChange={(e) => setWebsite(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lead-name" className="block text-[13px] font-semibold text-ink-soft mb-2">
|
||||
성함
|
||||
</label>
|
||||
<Input
|
||||
ref={firstFieldRef}
|
||||
id="lead-name"
|
||||
name="name"
|
||||
type="text"
|
||||
required
|
||||
autoComplete="name"
|
||||
placeholder="예: 홍길동"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={status === "submitting"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lead-email" className="block text-[13px] font-semibold text-ink-soft mb-2">
|
||||
이메일
|
||||
</label>
|
||||
<Input
|
||||
id="lead-email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder="예: hong@company.co.kr"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={status === "submitting"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{status === "error" && (
|
||||
<p role="alert" className="text-[13px] text-ink-soft leading-[1.6] break-keep">
|
||||
지금은 접수가 어렵습니다.{" "}
|
||||
<a href="#contact-section" onClick={onClose} className="text-primary font-semibold underline">
|
||||
상담 신청
|
||||
</a>
|
||||
으로 남겨주시면 동일하게 연락드립니다.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
className="w-full"
|
||||
disabled={!valid || status === "submitting"}
|
||||
>
|
||||
{status === "submitting" ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span>접수 중</span>
|
||||
</>
|
||||
) : (
|
||||
<span>데모 신청</span>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
@@ -3,13 +3,13 @@ import type * as React from "react"
|
||||
/** 데스크톱 브라우저 목업 프레임 — 신호등 버튼 + 주소창 + 16:10 워크스페이스. */
|
||||
function BrowserFrame({ url, children }: { url: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="bg-white rounded-2xl border border-line-strong shadow-[0_12px_40px_rgba(0,0,0,0.06)] overflow-hidden w-full max-w-2xl">
|
||||
<div className="bg-white rounded-card border border-line-strong shadow-[0_12px_40px_rgba(0,0,0,0.06)] overflow-hidden w-full max-w-2xl">
|
||||
<div className="bg-fill px-4 py-3.5 flex items-center justify-between border-b border-line-strong">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-3 h-3 rounded-full bg-[#FF5F56] inline-block" />
|
||||
<span className="w-3 h-3 rounded-full bg-[#FFBD2E] inline-block" />
|
||||
<span className="w-3 h-3 rounded-full bg-[#27C93F] inline-block" />
|
||||
<span className="text-[11px] text-ink-muted font-mono ml-3 font-semibold bg-white px-3 py-1 rounded-md border border-line-strong truncate max-w-[180px] sm:max-w-none">
|
||||
<span className="text-[11px] text-ink-muted font-mono ml-3 font-semibold bg-white px-3 py-1 rounded-control border border-line-strong truncate max-w-[180px] sm:max-w-none">
|
||||
{url}
|
||||
</span>
|
||||
</div>
|
||||
@@ -22,9 +22,9 @@ function BrowserFrame({ url, children }: { url: string; children: React.ReactNod
|
||||
/** 모바일 폰 목업 프레임 — 노치 포함 9:18 스크린. */
|
||||
function PhoneFrame({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="relative bg-black rounded-[48px] p-3 shadow-[0_20px_50px_rgba(0,0,0,0.15)] border-4 border-line-strong w-full max-w-[290px] aspect-[9/18] overflow-hidden flex flex-col">
|
||||
<div className="relative bg-black rounded-card p-3 shadow-[0_20px_50px_rgba(0,0,0,0.15)] border-4 border-line-strong w-full max-w-[290px] aspect-[9/18] overflow-hidden flex flex-col">
|
||||
{/* 노치는 화면 '안쪽'에 작은 아일랜드로 — 베젤과 붙으면 검은 덩어리처럼 보인다 */}
|
||||
<div className="bg-white rounded-[36px] flex-1 overflow-hidden relative flex flex-col justify-center items-center">
|
||||
<div className="bg-white rounded-card flex-1 overflow-hidden relative flex flex-col justify-center items-center">
|
||||
<div className="absolute top-1 left-1/2 -translate-x-1/2 bg-black/70 h-0.5 w-3.5 rounded-full z-20" />
|
||||
{children}
|
||||
</div>
|
||||
|
||||
@@ -2,16 +2,33 @@ import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
// 문의 폼 필드 공통 스타일 — 테두리 없는 회색 채움, 포커스 시 흰 배경 + 파란 링.
|
||||
/*
|
||||
* 문의 폼 필드.
|
||||
*
|
||||
* 회색 채움 박스는 어느 템플릿에나 있다. 밑줄 필드로 바꾸면 같은 기능인데 훨씬
|
||||
* 정돈돼 보인다 — 폼이 "입력 상자 더미"가 아니라 한 장의 문서처럼 읽힌다.
|
||||
*
|
||||
* 밑줄 폼의 알려진 위험은 입력란으로 안 보이는 것(어포던스 손실)인데,
|
||||
* 라벨을 항상 위에 두고 밑줄을 2px 로 두껍게 잡아 보완했다.
|
||||
* 두께를 항상 2px 로 고정해서 포커스 때 레이아웃이 흔들리지 않는다.
|
||||
*
|
||||
* 글자 16px 은 취향이 아니라 필수다 — iOS 사파리는 16px 미만 입력에 포커스하면
|
||||
* 화면을 자동 확대해서, 광고로 들어온 모바일 사용자의 폼 이탈을 만든다.
|
||||
*/
|
||||
const fieldClass =
|
||||
"w-full px-5 py-3.5 rounded-2xl bg-surface hover:bg-fill focus:bg-white border-0 focus:ring-2 focus:ring-primary/20 text-sm font-semibold text-ink transition-all placeholder:text-ink-faint outline-none"
|
||||
"w-full bg-transparent border-0 border-b-2 border-line-strong rounded-none px-0 py-3 " +
|
||||
"text-[16px] font-normal text-ink placeholder:text-ink-faint placeholder:font-normal " +
|
||||
"outline-none transition-colors hover:border-ink-muted focus:border-primary " +
|
||||
"disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
|
||||
function Input({ className, ...props }: React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
/* ComponentPropsWithRef 로 두면 ref 가 그대로 전달된다 (React 19 는 forwardRef 불필요).
|
||||
데모 요청 모달이 열릴 때 첫 필드로 포커스를 옮기려면 ref 가 필요하다. */
|
||||
function Input({ className, ...props }: React.ComponentPropsWithRef<"input">) {
|
||||
return <input className={cn(fieldClass, className)} {...props} />
|
||||
}
|
||||
|
||||
function Textarea({ className, ...props }: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
|
||||
return <textarea className={cn(fieldClass, "resize-none", className)} {...props} />
|
||||
function Textarea({ className, ...props }: React.ComponentPropsWithRef<"textarea">) {
|
||||
return <textarea className={cn(fieldClass, "resize-none leading-[1.6]", className)} {...props} />
|
||||
}
|
||||
|
||||
export { Input, Textarea }
|
||||
@@ -0,0 +1,179 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { motion, useReducedMotion } from "motion/react"
|
||||
import { Check } from "lucide-react"
|
||||
|
||||
import { DEMO_ITEMS, won } from "@/lib/negotiation-sim"
|
||||
import { EASE_OUT_EXPO } from "@/lib/motion"
|
||||
|
||||
/*
|
||||
* 협상 리플레이 — 자동 재생 결과 화면.
|
||||
*
|
||||
* 예전에는 negotiation_annotated_3d.mp4(677K)를 썼다. 영상이라 두 가지를 못 고쳤다.
|
||||
* - 화자가 "아이마켓 구매 MD" 로 픽셀에 구워져 있었다. POC 고객사 이름이라
|
||||
* 다른 MRO 회사에 영업할 때 쓸 수 없다.
|
||||
* - 색이 브랜드 팔레트 밖이었다. 실측하면 말풍선 #5A68CD, 목표가 라벨 #B96175,
|
||||
* 배지 #DB840B — 셋 다 토큰에 없는 색이고, 정작 브랜드의 핵심 대비 장치인
|
||||
* 민트(#0FFFD6, 상대편 색)는 한 번도 안 쓰였다.
|
||||
*
|
||||
* 컴포넌트로 옮기면 둘 다 뿌리에서 사라진다. 이름은 상수고 색은 토큰이라,
|
||||
* 팔레트를 바꾸면 여기도 같이 바뀐다. 에셋 677K 도 0 이 된다.
|
||||
*
|
||||
* 숫자는 지어내지 않고 DEMO_ITEMS[0] 을 그대로 쓴다 — 위쪽 인터랙티브 데모와 같은
|
||||
* 품목·같은 가격이라, 둘을 다 본 사람에게 앞뒤가 맞는다.
|
||||
*/
|
||||
|
||||
const ITEM = DEMO_ITEMS[0]
|
||||
const FINAL = ITEM.target // 1,080,000 — 데모의 목표가와 동일
|
||||
const SAVED = ITEM.listPrice - FINAL
|
||||
const RATE = (SAVED / ITEM.listPrice) * 100
|
||||
|
||||
type Line = { side: "buyer" | "supplier"; text: string; price: number }
|
||||
|
||||
/* 화자는 "구매 담당자" 로 둔다. 회사명을 넣으면 그 회사 전용 자산이 되고,
|
||||
특정 고객사 이름은 영업 대상이 바뀔 때마다 못 쓰게 된다. */
|
||||
const LINES: Line[] = [
|
||||
{ side: "supplier", text: `원자재가 올라서 이번 분기는 ${won(ITEM.listPrice)}원이 최선입니다.`, price: ITEM.listPrice },
|
||||
{ side: "buyer", text: `같은 사양 시장 최저가가 ${won(ITEM.marketLow)}원입니다. 연간 물량을 보증하면 어느 선까지 가능하신가요?`, price: ITEM.marketLow },
|
||||
{ side: "supplier", text: `공정상 한 번에 내리긴 어렵고, ${won(1_140_000)}원까지는 조정하겠습니다.`, price: 1_140_000 },
|
||||
{ side: "buyer", text: `목표가까지 얼마 남지 않았습니다. ${won(FINAL)}원이면 지금 바로 낙찰 처리하겠습니다.`, price: FINAL },
|
||||
{ side: "supplier", text: `좋습니다. ${won(FINAL)}원으로 맞추겠습니다.`, price: FINAL },
|
||||
]
|
||||
|
||||
const STEP_MS = 1600
|
||||
/** 마지막 줄 뒤 결과 카드가 머무는 시간. 짧으면 결론을 못 읽고 지나간다. */
|
||||
const HOLD_MS = 3200
|
||||
|
||||
export function NegotiationReplay({ className }: { className?: string }) {
|
||||
const reduce = useReducedMotion()
|
||||
const [shown, setShown] = useState(reduce ? LINES.length : 0)
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
const logRef = useRef<HTMLDivElement>(null)
|
||||
const [inView, setInView] = useState(false)
|
||||
|
||||
/* 화면 밖에서는 돌리지 않는다. 페이지 최하단이라 대부분의 시간 동안 보이지 않는데
|
||||
타이머만 계속 도는 건 배터리를 쓰는 일이다. */
|
||||
useEffect(() => {
|
||||
const el = rootRef.current
|
||||
if (!el) return
|
||||
const io = new IntersectionObserver(([e]) => setInView(e.isIntersecting), { threshold: 0.25 })
|
||||
io.observe(el)
|
||||
return () => io.disconnect()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (reduce || !inView) return
|
||||
const done = shown >= LINES.length
|
||||
const id = window.setTimeout(() => setShown((n) => (n >= LINES.length ? 0 : n + 1)), done ? HOLD_MS : STEP_MS)
|
||||
return () => clearTimeout(id)
|
||||
}, [shown, inView, reduce])
|
||||
|
||||
// 새 줄이 붙으면 바닥으로 붙인다.
|
||||
useEffect(() => {
|
||||
logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" })
|
||||
}, [shown])
|
||||
|
||||
const current = shown > 0 ? LINES[shown - 1].price : ITEM.listPrice
|
||||
const settled = shown >= LINES.length
|
||||
/* 정가에서 목표가까지 얼마나 내려왔는지. 1 을 넘지 않게 자른다. */
|
||||
const progress = Math.min(1, (ITEM.listPrice - current) / (ITEM.listPrice - FINAL))
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={className}
|
||||
role="img"
|
||||
aria-label={`협상 리플레이. 최초 제시가 ${won(ITEM.listPrice)}원에서 ${won(FINAL)}원으로 낙찰되어 ${won(SAVED)}원 절감된 예시입니다.`}
|
||||
>
|
||||
<div className="rounded-card border border-stage-line bg-stage-raised/70 backdrop-blur-sm p-5 sm:p-6">
|
||||
{/* 품목 + 목표가 — 구매 담당자가 위임한 기준이 무엇인지 먼저 보여준다. */}
|
||||
<div className="flex items-start justify-between gap-3 mb-4">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[14px] font-bold text-on-stage truncate">{ITEM.name}</div>
|
||||
<div className="text-[12px] text-on-stage-muted">{ITEM.spec}</div>
|
||||
</div>
|
||||
<div className="text-right shrink-0">
|
||||
<div className="text-[11px] font-semibold text-on-stage-muted">목표가</div>
|
||||
<div className="text-[14px] font-bold tabular-nums text-on-stage">{won(FINAL)}원</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 현재 제안가 + 진행 막대. 파랑에서 민트로 차오르며 양쪽이 만나는 지점을 그린다. */}
|
||||
<div className="mb-5">
|
||||
<div className="flex items-baseline justify-between mb-2">
|
||||
<span className="text-[11px] font-semibold text-on-stage-muted">현재 제안가</span>
|
||||
<span className="text-[22px] font-extrabold tabular-nums tracking-[-0.02em] text-on-stage">
|
||||
{won(current)}
|
||||
<span className="text-[14px] font-semibold text-on-stage-muted ml-0.5">원</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 rounded-full bg-white/10 overflow-hidden">
|
||||
<motion.div
|
||||
className="h-full rounded-full bg-linear-to-r from-primary-on-stage to-counter"
|
||||
animate={{ width: `${progress * 100}%` }}
|
||||
transition={{ duration: 0.6, ease: EASE_OUT_EXPO }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 대화. 높이를 고정해 줄이 늘어도 레이아웃이 튀지 않는다. */}
|
||||
<div ref={logRef} className="h-[210px] overflow-hidden space-y-3 scrollbar-none">
|
||||
{LINES.slice(0, shown).map((line, i) => (
|
||||
<motion.div
|
||||
key={i}
|
||||
initial={reduce ? false : { opacity: 0, y: 8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3, ease: EASE_OUT_EXPO }}
|
||||
className={`flex flex-col ${line.side === "buyer" ? "items-start" : "items-end"}`}
|
||||
>
|
||||
<span
|
||||
className={`text-[11px] font-semibold mb-1 ${
|
||||
line.side === "buyer" ? "text-primary-on-stage" : "text-counter"
|
||||
}`}
|
||||
>
|
||||
{line.side === "buyer" ? "구매 담당자" : "협력사"}
|
||||
</span>
|
||||
<div
|
||||
className={`max-w-[90%] rounded-card px-3.5 py-2.5 text-[13px] leading-[1.55] break-keep ${
|
||||
line.side === "buyer"
|
||||
? "bg-primary text-white"
|
||||
: "bg-counter-surface text-counter border border-counter/20"
|
||||
}`}
|
||||
>
|
||||
{line.text}
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 낙찰 카드. 자리를 항상 차지하게 두고 내용만 켜고 끈다 — 나타날 때 아래 요소가
|
||||
밀리면 페이지 전체가 주기적으로 흔들린다. */}
|
||||
<div className="mt-4 h-[74px]">
|
||||
{settled && (
|
||||
<motion.div
|
||||
initial={reduce ? false : { opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4, ease: EASE_OUT_EXPO }}
|
||||
className="h-full rounded-card border border-counter/25 bg-counter-surface px-3.5 py-3 flex items-center gap-2.5"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-full bg-counter/15 text-counter flex items-center justify-center shrink-0">
|
||||
<Check className="w-4 h-4" />
|
||||
</div>
|
||||
{/* 금액은 줄바꿈을 막는다. 카드 높이가 74px 로 고정이라(등장할 때 아래가 밀리지
|
||||
않게 하려고) 한 줄이라도 접히면 잘린다. 좁으면 접히는 게 아니라 붙어야 한다. */}
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] font-semibold text-counter mb-0.5 whitespace-nowrap">협상 타결 → 낙찰</div>
|
||||
<div className="text-[16px] font-extrabold tabular-nums text-on-stage whitespace-nowrap">{won(FINAL)}원</div>
|
||||
</div>
|
||||
<div className="text-right shrink-0 ml-auto">
|
||||
<div className="text-[11px] font-semibold text-on-stage-muted mb-0.5 whitespace-nowrap">절감액</div>
|
||||
<div className="text-[15px] font-extrabold tabular-nums text-counter whitespace-nowrap">
|
||||
{won(SAVED)}원 <span className="text-[12px]">▼{RATE.toFixed(1)}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { useEffect, useRef, useState, type RefObject } from "react"
|
||||
|
||||
/* 파이프라인 6단계. 원래 히어로 캔버스가 소유하던 타입인데, 히어로가 영상으로 바뀌면서
|
||||
이리로 옮겼다 — 단계 이름을 실제로 쓰는 건 이제 이 링뿐이다. */
|
||||
export type DataFlowPhase = "scatter" | "cluster" | "stream" | "card" | "negotiate" | "learn"
|
||||
|
||||
/**
|
||||
* 파이프라인 순환 링 — 정원.
|
||||
*
|
||||
* 앞서 3D 로 눕힌 타원을 썼는데, 깊이는 생기지만 정원의 완결감이 사라진다.
|
||||
* negotium 의 메시지는 "닫힌 루프"라서 완결감 쪽이 맞다.
|
||||
*
|
||||
* 구조는 레퍼런스(infinith)와 같다 — 점선 원만 천천히 돌고, 마디와 글자는 고정이다.
|
||||
* 글자까지 같이 돌면 읽을 수가 없다.
|
||||
*/
|
||||
|
||||
const NODES: { key: DataFlowPhase; label: string }[] = [
|
||||
{ key: "scatter", label: "Collect" },
|
||||
{ key: "cluster", label: "Classify" },
|
||||
{ key: "stream", label: "Benchmark" },
|
||||
{ key: "card", label: "Anchor" },
|
||||
{ key: "negotiate", label: "Negotiate" },
|
||||
{ key: "learn", label: "Learn" },
|
||||
]
|
||||
|
||||
/* viewBox 는 정사각이 아니다. 라벨이 궤도 바깥 좌우로 뻗기 때문에 가로 여백이 더 필요한데,
|
||||
정사각으로 두면 "Benchmark" 같은 긴 라벨이 잘린다(SVG 는 viewBox 밖을 그냥 자른다).
|
||||
가로만 넓히면 링 크기는 유지한 채 라벨 자리를 확보할 수 있다. */
|
||||
const VB_W = 176
|
||||
const VB_H = 150
|
||||
const CX = VB_W / 2
|
||||
const CY = VB_H / 2
|
||||
const R = 46 // 궤도 반지름
|
||||
const R_LABEL = 58 // 라벨은 궤도 바깥에
|
||||
|
||||
const rad = (ratio: number) => ratio * Math.PI * 2 - Math.PI / 2 // 12시에서 시계방향
|
||||
const at = (ratio: number, radius: number) => ({
|
||||
x: CX + Math.cos(rad(ratio)) * radius,
|
||||
y: CY + Math.sin(rad(ratio)) * radius,
|
||||
})
|
||||
|
||||
const LOOP_MS = 10_500 // 히어로 캔버스와 같은 주기
|
||||
|
||||
export function OrbitRing({
|
||||
phase,
|
||||
progressRef,
|
||||
className = "",
|
||||
}: {
|
||||
/** 밖에서 단계를 주면 그걸 따르고, 없으면 자체 시계로 돈다. */
|
||||
phase?: DataFlowPhase
|
||||
/** 캔버스가 매 프레임 써 넣는 루프 진행도 0..1. 없으면 스스로 센다. */
|
||||
progressRef?: RefObject<number>
|
||||
className?: string
|
||||
}) {
|
||||
const headRef = useRef<SVGCircleElement>(null)
|
||||
const [ownIndex, setOwnIndex] = useState(0)
|
||||
|
||||
const activeIndex = phase ? Math.max(0, NODES.findIndex((n) => n.key === phase)) : ownIndex
|
||||
|
||||
/* 궤도를 도는 머리는 rAF 로 직접 갱신한다 — 60fps 로 setState 를 부르면 페이지가 매 프레임 리렌더된다.
|
||||
단계 라벨만 바뀔 때(초당 0.5회) 리렌더한다. */
|
||||
useEffect(() => {
|
||||
let raf = 0
|
||||
let last = -1
|
||||
const startedAt = performance.now()
|
||||
const tick = (now: number) => {
|
||||
const p = progressRef ? (progressRef.current ?? 0) : ((now - startedAt) % LOOP_MS) / LOOP_MS
|
||||
const { x, y } = at(p, R)
|
||||
if (headRef.current) {
|
||||
headRef.current.setAttribute("cx", String(x))
|
||||
headRef.current.setAttribute("cy", String(y))
|
||||
}
|
||||
if (!phase) {
|
||||
const i = Math.min(NODES.length - 1, Math.floor(p * NODES.length))
|
||||
if (i !== last) {
|
||||
last = i
|
||||
setOwnIndex(i)
|
||||
}
|
||||
}
|
||||
raf = requestAnimationFrame(tick)
|
||||
}
|
||||
raf = requestAnimationFrame(tick)
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [progressRef, phase])
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${VB_W} ${VB_H}`} className={className} role="img" aria-label="협상 파이프라인 순환">
|
||||
<defs>
|
||||
<linearGradient id="orbitGrad" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stopColor="var(--color-primary-on-stage)" stopOpacity="0.9" />
|
||||
<stop offset="55%" stopColor="var(--color-on-stage-soft)" stopOpacity="0.35" />
|
||||
<stop offset="100%" stopColor="var(--color-counter)" stopOpacity="0.55" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
{/* 점선 궤도 — 이 레이어만 돈다 */}
|
||||
<g className="animate-[spin_22s_linear_infinite] motion-reduce:animate-none" style={{ transformOrigin: `${CX}px ${CY}px` }}>
|
||||
<circle cx={CX} cy={CY} r={R} fill="none" stroke="url(#orbitGrad)" strokeWidth="0.6" strokeDasharray="2.2 2.4" />
|
||||
</g>
|
||||
|
||||
{/* 바깥 보조 호 — 정지. 원이 하나면 심심하고, 둘이면 공간이 생긴다. */}
|
||||
<circle
|
||||
cx={CX}
|
||||
cy={CY}
|
||||
r={R + 9}
|
||||
fill="none"
|
||||
stroke="var(--color-on-stage-soft)"
|
||||
strokeOpacity="0.1"
|
||||
strokeWidth="0.4"
|
||||
/>
|
||||
|
||||
{/* 마디 + 라벨 — 고정 레이어 */}
|
||||
{NODES.map((n, i) => {
|
||||
const ratio = i / NODES.length
|
||||
const p = at(ratio, R)
|
||||
const l = at(ratio, R_LABEL)
|
||||
const cos = Math.cos(rad(ratio))
|
||||
const anchor = cos > 0.3 ? "start" : cos < -0.3 ? "end" : "middle"
|
||||
const active = i === activeIndex
|
||||
return (
|
||||
<g key={n.key}>
|
||||
<circle
|
||||
cx={p.x}
|
||||
cy={p.y}
|
||||
r={active ? 2.6 : 1.4}
|
||||
fill={active ? "var(--color-primary-on-stage)" : "var(--color-on-stage-soft)"}
|
||||
opacity={active ? 1 : 0.45}
|
||||
style={{ transition: "r 240ms ease-out, opacity 240ms ease-out" }}
|
||||
/>
|
||||
<text
|
||||
x={l.x}
|
||||
y={l.y + 1.6}
|
||||
textAnchor={anchor}
|
||||
fontSize="5"
|
||||
fontWeight={active ? 700 : 500}
|
||||
fill={active ? "#FFFFFF" : "var(--color-on-stage-soft)"}
|
||||
opacity={active ? 1 : 0.5}
|
||||
style={{ transition: "opacity 240ms ease-out" }}
|
||||
>
|
||||
{n.label}
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* 궤도를 도는 머리 */}
|
||||
<circle ref={headRef} cx={CX} cy={CY - R} r="2" fill="#FFFFFF" opacity="0.95" />
|
||||
|
||||
{/* 가운데 */}
|
||||
<text x={CX} y={CY - 1} textAnchor="middle" fontSize="7" fontWeight="700" fill="#FFFFFF">
|
||||
{NODES[activeIndex].label}
|
||||
</text>
|
||||
<text
|
||||
x={CX}
|
||||
y={CY + 8.5}
|
||||
textAnchor="middle"
|
||||
fontSize="4.2"
|
||||
fontWeight="500"
|
||||
fill="var(--color-on-stage-soft)"
|
||||
opacity="0.5"
|
||||
>
|
||||
{String(activeIndex + 1).padStart(2, "0")} / {String(NODES.length).padStart(2, "0")}
|
||||
</text>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
type RangeSliderProps = {
|
||||
min: number
|
||||
max: number
|
||||
step: number
|
||||
value: number
|
||||
onChange: (value: number) => void
|
||||
}
|
||||
|
||||
/** 채워진 트랙이 값을 따라가는 파란 슬라이더 (ROI 시뮬레이터·히어로 콘솔 공용). */
|
||||
function RangeSlider({ min, max, step, value, onChange }: RangeSliderProps) {
|
||||
const filled = ((value - min) / (max - min)) * 100
|
||||
return (
|
||||
<input
|
||||
type="range"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={value}
|
||||
onChange={(e) => onChange(Number(e.target.value))}
|
||||
className="w-full h-1.5 rounded-lg appearance-none cursor-pointer accent-primary transition-all"
|
||||
style={{
|
||||
background: `linear-gradient(to right, var(--color-primary) 0%, var(--color-primary) ${filled}%, var(--color-line-strong) ${filled}%, var(--color-line-strong) 100%)`,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { RangeSlider }
|
||||
@@ -3,25 +3,102 @@ import * as React from "react"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
/*
|
||||
* 섹션 머리.
|
||||
*
|
||||
* eyebrow 는 선택이고, 기본적으로 쓰지 않는다. 작은 색 라벨을 섹션마다 반복하면
|
||||
* 레퍼런스에서는 영문 대문자라 조판 요소로 기능하지만, 한글은 대문자가 없어서
|
||||
* 그냥 "작은 글씨"가 되고 일곱 번 반복되면 벽지가 된다.
|
||||
* 위계는 라벨이 아니라 헤드라인 크기(본문의 3.5~4배)와 2톤 대비로 만든다.
|
||||
*
|
||||
* ── 세로 리듬 ────────────────────────────────────────────────────────
|
||||
* 머리 안팎의 간격은 전부 이 파일이 소유한다. 섹션 파일에서 각자 mb-12 / mb-16 /
|
||||
* mb-20 / mb-24 를 붙이던 걸 걷어낸 결과다. 같은 관계(머리 → 본문)에 값이 다섯 개
|
||||
* 있으면 스크롤할 때 섹션마다 호흡이 달라지고, 그게 "정돈이 안 됐다"는 인상의
|
||||
* 실제 원인이었다.
|
||||
*
|
||||
* 규칙은 하나다 — 간격이 위계를 만든다. 가까울수록 한 덩어리로 읽힌다.
|
||||
* 값이 흔들리면 "어디까지가 한 덩어리인가"가 섹션마다 달라져 보인다.
|
||||
*
|
||||
* eyebrow → title 16px 라벨은 제목에 붙는다
|
||||
* title → description 20 / 32px 큰 활자는 더 벌린다. 64px 제목 아래 20px 은 붙어 보인다
|
||||
* 머리 → 본문 56 / 80px 섹션 안에서 가장 큰 끊김
|
||||
*
|
||||
* 섹션 파일에서 이 관계들에 mb-· mt- 유틸리티를 직접 쓰지 않는다. 필요하면 아래 상수를
|
||||
* import 해서 쓰고, 새 값이 필요하다고 느껴지면 여기에 이름을 붙여서 추가한다.
|
||||
* 눈대중으로 한 칸씩 조정하기 시작하면 다시 지금 상태로 돌아온다.
|
||||
*/
|
||||
|
||||
/** 머리 → 본문. 머리를 직접 조판하는 섹션(무대 데모)도 이 상수를 쓴다. */
|
||||
export const HEADING_GAP = "mb-14 md:mb-20"
|
||||
/** 탭·토글 행 → 본문. 머리 간격보다 좁아서 컨트롤이 위가 아니라 본문 쪽에 묶인다. */
|
||||
export const CONTROL_GAP = "mb-12"
|
||||
/** 리드 문단 → 버튼 행 (히어로·최종 CTA). */
|
||||
export const CTA_GAP = "mt-12"
|
||||
/** display 티어 제목 → 리드 문단. 히어로는 h1 이라 SectionHeading 을 못 쓰고 이 상수를 직접 쓴다. */
|
||||
export const DISPLAY_LEAD_GAP = "mt-8"
|
||||
|
||||
/*
|
||||
* 제목 조판 티어. 티어가 바뀌면 리드 문단까지의 간격도 같이 움직인다 —
|
||||
* Typography 주석의 "크기·굵기·조임은 같이 움직인다"와 같은 이유로, 간격도 딸려간다.
|
||||
*/
|
||||
const SIZES = {
|
||||
/** 섹션 표준 h2 (34 / 64px) */
|
||||
title: { variant: "title", descriptionGap: "mt-5" },
|
||||
/** 히어로·최종 CTA 급 디스플레이 (38~74px) */
|
||||
display: { variant: "stageDisplay", descriptionGap: DISPLAY_LEAD_GAP },
|
||||
} as const
|
||||
|
||||
type SectionHeadingProps = {
|
||||
eyebrow: string
|
||||
eyebrow?: string
|
||||
title: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
align?: "left" | "center"
|
||||
/** 다크 무대 섹션(bg="stage")에서는 "stage" 를 준다. Typography 변형이 먹색을 물고 있어서 필요하다. */
|
||||
tone?: "light" | "stage"
|
||||
/** 제목 조판 티어. display 는 히어로·최종 CTA 전용. */
|
||||
size?: keyof typeof SIZES
|
||||
/** 머리 아래 표준 간격을 끈다. 뒤에 컨트롤 행이 붙는 섹션에서만 쓴다. */
|
||||
gap?: "heading" | "none"
|
||||
className?: string
|
||||
/** 리드 문단 폭 제한 등 (예: "max-w-2xl") */
|
||||
/** 제목 크기 미세조정 (예: 최종 CTA 의 축소 디스플레이) */
|
||||
titleClassName?: string
|
||||
/** 리드 문단 폭 제한·색 조정 (예: "max-w-2xl"). 세로 간격은 여기서 주지 않는다. */
|
||||
descriptionClassName?: string
|
||||
}
|
||||
|
||||
function SectionHeading({ eyebrow, title, description, align = "left", className, descriptionClassName }: SectionHeadingProps) {
|
||||
function SectionHeading({
|
||||
eyebrow,
|
||||
title,
|
||||
description,
|
||||
align = "left",
|
||||
tone = "light",
|
||||
size = "title",
|
||||
gap = "heading",
|
||||
className,
|
||||
titleClassName,
|
||||
descriptionClassName,
|
||||
}: SectionHeadingProps) {
|
||||
const onStage = tone === "stage"
|
||||
const { variant, descriptionGap } = SIZES[size]
|
||||
|
||||
return (
|
||||
<div className={cn(align === "center" && "text-center", className)}>
|
||||
<Typography variant="eyebrow" className="mb-3 block">
|
||||
{eyebrow}
|
||||
<div className={cn(align === "center" && "text-center", gap === "heading" && HEADING_GAP, className)}>
|
||||
{/* eyebrow 가 없을 때 빈 span 을 렌더하면 mb + 30px 행간만큼 유령 여백이 생긴다.
|
||||
지금은 모든 섹션이 eyebrow 를 넘기지만, 하나만 빼도 그 섹션만 제목이 내려앉는다. */}
|
||||
{eyebrow && (
|
||||
<Typography variant="eyebrow" className={cn("mb-4 block", onStage && "text-primary-on-stage")}>
|
||||
{eyebrow}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant={variant} as="h2" className={cn(onStage && "text-on-stage", titleClassName)}>
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography variant="title">{title}</Typography>
|
||||
{description && (
|
||||
<Typography variant="lead" className={cn("mt-5", align === "center" && "mx-auto", descriptionClassName)}>
|
||||
<Typography
|
||||
variant="lead"
|
||||
className={cn(descriptionGap, align === "center" && "mx-auto", onStage && "text-on-stage-soft", descriptionClassName)}
|
||||
>
|
||||
{description}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
@@ -6,6 +6,8 @@ const sectionBg = {
|
||||
white: "bg-white",
|
||||
surface: "bg-surface",
|
||||
dark: "bg-ink text-white",
|
||||
/** 히어로와 같은 무대. 어두운 섹션은 이걸 쓴다 — 페이지 안에 어둠이 두 종류면 따로 논다. */
|
||||
stage: "stage-bg text-on-stage",
|
||||
}
|
||||
|
||||
const sectionWidth = {
|
||||
@@ -37,7 +39,8 @@ function Section({
|
||||
}: SectionProps) {
|
||||
return (
|
||||
<section
|
||||
className={cn("py-36 md:py-44", sectionBg[bg], bordered && "border-t border-line", decor && "relative overflow-hidden", className)}
|
||||
/* 레퍼런스 섹션 패딩은 104~139px. 176px 은 과해서 "채울 내용이 없어" 보인다. */
|
||||
className={cn("py-24 md:py-32", sectionBg[bg], bordered && "border-t border-line", decor && "relative overflow-hidden", className)}
|
||||
{...props}
|
||||
>
|
||||
{decor}
|
||||
|
||||
@@ -56,7 +56,7 @@ function SlateLeaf({ leaf }: { leaf: SlateText }) {
|
||||
children = <em className="italic">{children}</em>
|
||||
}
|
||||
if (leaf.code) {
|
||||
children = <code className="bg-primary/10 px-1.5 py-0.5 rounded-lg font-mono text-xs text-primary font-bold">{children}</code>
|
||||
children = <code className="bg-primary/10 px-1.5 py-0.5 rounded-control font-mono text-xs text-primary font-bold">{children}</code>
|
||||
}
|
||||
|
||||
return <span>{children}</span>
|
||||
|
||||
@@ -3,28 +3,60 @@ import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
// 랜딩 텍스트 스케일 단일 소스. 페이지마다 text-[44px]/font-black/…을 직접 박지 말고
|
||||
// variant 로 통일한다. 색·크기 미세조정은 className 으로 합성.
|
||||
/*
|
||||
* 랜딩 텍스트 스케일 단일 소스. 페이지마다 text-[44px]/font-black/…을 직접 박지 말고
|
||||
* variant 로 통일한다. 색·크기 미세조정은 className 으로 합성.
|
||||
*
|
||||
* 값은 레퍼런스(statworx.com) 실측에서 가져왔다. 핵심 규칙 셋:
|
||||
*
|
||||
* 1) 크기·굵기·조임은 같이 움직인다. 44px 에 900 은 뭉툭하지만, 72px 에 800 +
|
||||
* 자간 -0.044em + 행간 1.0 은 확신으로 읽힌다(jitter.video 실측: 72px/800/-0.044em/0.95).
|
||||
* 굵기만 올리면 둔해지고, 크기만 올리면 헐거워진다.
|
||||
* 1-1) 크기 판단은 "글자가 화면 폭의 몇 %를 쓰는가"로 한다(레퍼런스 statworx 는 48%).
|
||||
* 주의: h1 은 블록이라 getBoundingClientRect 로 재면 컨테이너 폭이 나온다.
|
||||
* Range 로 텍스트 노드를 재야 실제 글자 폭이다 — 이걸 헷갈리면 엉뚱한 값으로 조정하게 된다.
|
||||
* 지금 74px 에서 약 40%. 답답함의 원인은 가로 비율이 아니라 세로 간격이었다.
|
||||
* 2) 한글 줄바꿈은 break-keep 만으로 부족하다. break-keep 은 어절 안에서 안 쪼개지게
|
||||
* 할 뿐 어디서 넘어갈지는 못 정해서 "에이전트는 기준 / 밖으로 안 나갑니다" 같은
|
||||
* 어색한 분절이 나온다. text-balance 를 같이 걸어 줄 길이를 고르게 맞춘다.
|
||||
* 3) 크면 조인다. 디스플레이는 자간 -0.042em·행간 1.0 까지 조이고, 작아질수록 푼다.
|
||||
* 단 한글은 행간 0.95 를 못 쓴다 — 라틴은 어센더·디센더가 여백을 만들지만
|
||||
* 한글은 네모틀을 꽉 채워 줄이 붙는다. 라틴 기준 0.95~1.0 을 그대로 쓰면
|
||||
* 두 줄짜리 한글 헤드라인이 서로 닿아 답답해진다. 1.07 이 붙지도 벌어지지도 않는 지점.
|
||||
* 3) 라벨은 작고 자간은 normal. 레퍼런스 아이브로우가 10.4px/600/자간 normal 이다.
|
||||
* 14px + tracking-wider + 알약 배경 + 반짝이 아이콘 조합이 전형적인 AI 생성 티다.
|
||||
*
|
||||
* 한글 보정: 본문은 레퍼런스(13.9px)보다 키운다. 한글은 14px 미만에서 판독성이 급격히
|
||||
* 떨어진다. 대신 디스플레이를 더 키워 대비(디스플레이:본문 ≈ 4.5:1)를 만든다.
|
||||
*/
|
||||
const typographyVariants = cva("", {
|
||||
variants: {
|
||||
variant: {
|
||||
// 히어로 h1
|
||||
display: "text-3xl sm:text-4xl md:text-[50px] font-black tracking-tight leading-[1.2] text-ink break-keep",
|
||||
// 라이트 섹션 h1
|
||||
display: "text-[44px] sm:text-[58px] md:text-[68px] font-extrabold tracking-[-0.04em] leading-[1.14] text-ink break-keep text-balance",
|
||||
// 다크 무대 히어로 h1. 색은 쓰는 쪽에서 준다(2톤 헤드라인).
|
||||
stageDisplay:
|
||||
"text-[38px] sm:text-[52px] md:text-[64px] lg:text-[74px] font-extrabold tracking-[-0.042em] leading-[1.1] break-keep text-balance",
|
||||
// 섹션 제목 h2
|
||||
title: "text-3xl md:text-[44px] font-black tracking-tight leading-tight text-ink break-keep",
|
||||
/* 본문(15px)의 4.3배. 대비는 굵기가 아니라 크기로 만든다 —
|
||||
굵기를 올리면 뭉툭해지고, 크기를 올리면 확신이 생긴다.
|
||||
커질수록 자간을 더 조인다: 52px 에서 적당한 -0.021em 도 64px 에선 헐거워 보인다. */
|
||||
title: "text-[34px] md:text-[64px] font-extrabold tracking-[-0.042em] leading-[1.16] text-ink break-keep text-balance",
|
||||
// 섹션 내 서브 제목 (데모 패널 등)
|
||||
heading: "text-2xl md:text-3xl font-bold tracking-tight text-ink break-keep",
|
||||
heading: "text-[24px] md:text-[32px] font-bold tracking-[-0.034em] leading-[1.14] text-ink break-keep text-balance",
|
||||
// 카드 제목
|
||||
cardTitle: "text-lg font-bold text-ink break-keep",
|
||||
// 섹션 상단 오버라인 라벨
|
||||
eyebrow: "text-sm font-semibold text-primary tracking-wider uppercase",
|
||||
cardTitle: "text-[20px] font-bold tracking-[-0.028em] leading-[1.3] text-ink break-keep",
|
||||
/* 섹션 상단 라벨. 영문 전용 — 한글 내용은 title 이 맡고, 여기는 조판 요소다.
|
||||
작은 대문자 산세리프 라벨은 어느 SaaS 랜딩에나 있다. 세리프 이탤릭으로 두면
|
||||
같은 자리에서 장식이 아니라 편집 디자인처럼 읽힌다. 한글은 넣지 않는다. */
|
||||
eyebrow: "font-display italic text-[24px] md:text-[30px] font-normal text-primary tracking-[0.005em]",
|
||||
// 섹션 리드 문단
|
||||
lead: "text-base sm:text-lg text-ink-soft font-medium leading-relaxed break-keep",
|
||||
body: "text-[15px] text-ink-soft font-medium leading-relaxed break-keep",
|
||||
small: "text-sm text-ink-soft font-medium leading-relaxed break-keep",
|
||||
caption: "text-xs text-ink-muted font-semibold leading-relaxed break-keep",
|
||||
// 11px 트래킹 대문자 메타 라벨 (단가 패널·푸터 컬럼 제목 등)
|
||||
micro: "text-[11px] font-bold text-ink-muted uppercase tracking-wider",
|
||||
lead: "text-[16px] sm:text-[17px] text-ink-soft font-normal leading-[1.6] break-keep",
|
||||
body: "text-[15px] text-ink-soft font-normal leading-[1.6] break-keep",
|
||||
small: "text-[14px] text-ink-soft font-normal leading-[1.6] break-keep",
|
||||
caption: "text-[12.5px] text-ink-muted font-normal leading-[1.55] break-keep",
|
||||
// 메타 라벨 (단가 패널·푸터 컬럼 제목 등)
|
||||
micro: "text-[11px] font-semibold text-ink-muted tracking-normal",
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: "body" },
|
||||
@@ -32,6 +64,7 @@ const typographyVariants = cva("", {
|
||||
|
||||
const defaultTag: Record<NonNullable<VariantProps<typeof typographyVariants>["variant"]>, React.ElementType> = {
|
||||
display: "h1",
|
||||
stageDisplay: "h1",
|
||||
title: "h2",
|
||||
heading: "h3",
|
||||
cardTitle: "h3",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 리드 전송 — 데모 요청 모달과 상담 신청 폼이 함께 쓴다.
|
||||
*
|
||||
* 목적지는 같은 오리진의 서버리스 함수(api/lead.ts)다. 랜딩은 ssr:false 정적 빌드지만
|
||||
* Vercel 의 /api 디렉터리 함수는 별개로 배포되므로 서버 없이도 POST 를 받을 수 있다.
|
||||
* 같은 오리진이라 엔드포인트 환경변수도, CORS 도 필요 없다.
|
||||
*
|
||||
* 성공을 위조하지 않는다. 예전 상담 신청 폼은 1.2초 뒤 성공 화면만 띄우고 아무 데도
|
||||
* 보내지 않았다 — 화면은 "접수되었습니다"인데 영업이 받을 리드는 없었다.
|
||||
* 여기서는 서버가 리드를 확보했을 때만 ok 를 돌려준다.
|
||||
*/
|
||||
|
||||
const ENDPOINT = "/api/lead"
|
||||
|
||||
export type LeadSource = "demo-request" | "contact"
|
||||
|
||||
export type Lead = {
|
||||
source: LeadSource
|
||||
name: string
|
||||
email: string
|
||||
company?: string
|
||||
phone?: string
|
||||
message?: string
|
||||
/** 봇 함정. 화면에서 감춘 필드라 값이 차 있으면 자동 제출이다. 서버가 조용히 버린다. */
|
||||
website?: string
|
||||
}
|
||||
|
||||
export type LeadResult = { ok: true } | { ok: false; reason: "invalid" | "network" | "rejected" }
|
||||
|
||||
/** 느슨한 검사. 정규식으로 이메일을 엄밀히 검증하려는 시도는 늘 진짜 주소를 막는다. */
|
||||
export function isEmailLike(value: string) {
|
||||
const v = value.trim()
|
||||
return v.length >= 5 && v.includes("@") && !v.startsWith("@") && !v.endsWith("@") && !/\s/.test(v)
|
||||
}
|
||||
|
||||
export async function submitLead(lead: Lead): Promise<LeadResult> {
|
||||
if (!lead.name.trim() || !isEmailLike(lead.email)) return { ok: false, reason: "invalid" }
|
||||
|
||||
try {
|
||||
const res = await fetch(ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(lead),
|
||||
})
|
||||
return res.ok ? { ok: true } : { ok: false, reason: "rejected" }
|
||||
} catch {
|
||||
// 로컬 dev(react-router dev)에는 /api 가 없어서 여기로 온다. 확인은 `vercel dev` 로.
|
||||
return { ok: false, reason: "network" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* 랜딩 협상 데모의 규칙 엔진 (클라이언트 전용).
|
||||
*
|
||||
* 실제 negotium 엔진(agent 서비스)의 판정 규칙을 그대로 옮겼다. 데모가 제품과 다른
|
||||
* 규칙으로 돌면 상담 자리에서 거짓말이 되기 때문에, 단순화는 하되 규칙은 바꾸지 않는다.
|
||||
*
|
||||
* - 앵커링가(anchor) 이하 제시는 무조건 수락한다.
|
||||
* - 앵커 위면 협상 카드를 한 장 쓰고 역제안한다. 카드는 3장.
|
||||
* - 카드를 다 쓰고도 앵커 위면 개찰(낙찰자 미정 마감)이다. 결렬이 아니다.
|
||||
*
|
||||
* React 를 모른다. 나중에 서버의 실엔진(/api/demo/negotiate)으로 갈아끼울 때
|
||||
* 이 파일의 함수 시그니처만 유지하면 컴포넌트는 손대지 않아도 된다.
|
||||
*/
|
||||
|
||||
export type Role = "buyer" | "seller"
|
||||
|
||||
export type DemoItem = {
|
||||
id: string
|
||||
name: string
|
||||
spec: string
|
||||
/** 협력사 최초 제시가 */
|
||||
listPrice: number
|
||||
/** LPS 인터넷 최저가 — 에이전트가 근거로 인용한다 */
|
||||
marketLow: number
|
||||
/** 앵커링가. 이 이하면 무조건 낙찰 */
|
||||
anchor: number
|
||||
/** 견적 생성 때 정한 목표가 */
|
||||
target: number
|
||||
}
|
||||
|
||||
export const MAX_CARDS = 3
|
||||
|
||||
export const DEMO_ITEMS: DemoItem[] = [
|
||||
{
|
||||
id: "glove",
|
||||
name: "니트릴 코팅 안전장갑",
|
||||
spec: "1,000켤레 · 월 정기",
|
||||
listPrice: 1_200_000,
|
||||
marketLow: 1_110_000,
|
||||
anchor: 1_020_000,
|
||||
target: 1_080_000,
|
||||
},
|
||||
{
|
||||
id: "paper",
|
||||
name: "A4 복사용지 80g",
|
||||
spec: "500박스 · 분기 발주",
|
||||
listPrice: 8_750_000,
|
||||
marketLow: 8_200_000,
|
||||
anchor: 7_900_000,
|
||||
target: 8_100_000,
|
||||
},
|
||||
{
|
||||
id: "oil",
|
||||
name: "산업용 윤활유 20L",
|
||||
spec: "300통 · 반기 발주",
|
||||
listPrice: 5_400_000,
|
||||
marketLow: 5_050_000,
|
||||
anchor: 4_850_000,
|
||||
target: 4_980_000,
|
||||
},
|
||||
]
|
||||
|
||||
export type Turn = {
|
||||
id: number
|
||||
side: "agent" | "counterpart"
|
||||
text: string
|
||||
/** 이 턴에서 테이블에 올라온 가격 */
|
||||
price?: number
|
||||
}
|
||||
|
||||
export type Outcome = "running" | "award" | "open"
|
||||
|
||||
/** 협상에서 실제로 오가는 조건들. 가격만 깎는 게 아니라는 걸 보여주는 장치. */
|
||||
const LEVERS = ["연간 물량 보증", "납기 2주 연장", "대금 지급일 15일 단축"] as const
|
||||
|
||||
/** 10원 단위 반올림 — 실제 엔진의 앵커링 정돈 규칙과 같다. */
|
||||
export const round10 = (n: number) => Math.round(n / 10) * 10
|
||||
|
||||
export const won = (n: number) => n.toLocaleString("ko-KR")
|
||||
|
||||
/**
|
||||
* 에이전트의 양보 곡선 — 이 데모의 성격을 결정하는 단 하나의 숫자 뭉치다.
|
||||
*
|
||||
* 카드를 쓸수록 앵커에서 상대 제시가 쪽으로 얼마나 올라올지를 정한다.
|
||||
* 0 이면 끝까지 앵커를 고수하고, 1 이면 즉시 상대 제시가를 받는다.
|
||||
* 앞 카드를 낮게 잡을수록 강하게 버티는 에이전트가 된다.
|
||||
*/
|
||||
const CONCESSION = [0, 0.34, 0.62]
|
||||
|
||||
/** 협력사(사용자) 제시가에 대한 에이전트의 판정. seller 모드의 핵심. */
|
||||
export function respondToOffer(
|
||||
item: DemoItem,
|
||||
offer: number,
|
||||
cardsUsed: number,
|
||||
): { outcome: Outcome; price: number; text: string } {
|
||||
if (offer <= item.anchor) {
|
||||
return {
|
||||
outcome: "award",
|
||||
price: offer,
|
||||
text: `${won(offer)}원으로 확정하겠습니다. 목표가 ${won(item.target)}원 대비 ${won(
|
||||
item.target - offer,
|
||||
)}원 낮습니다. 주고받은 제안은 전부 기록에 남습니다.`,
|
||||
}
|
||||
}
|
||||
|
||||
if (cardsUsed >= MAX_CARDS) {
|
||||
return {
|
||||
outcome: "open",
|
||||
price: offer,
|
||||
text: `${won(offer)}원은 이번 견적의 낙찰 기준을 넘습니다. 협상 카드를 다 썼으니 이 건은 개찰로 마감하고 담당자에게 넘기겠습니다.`,
|
||||
}
|
||||
}
|
||||
|
||||
const ask = round10(item.anchor + (offer - item.anchor) * CONCESSION[cardsUsed])
|
||||
const lever = LEVERS[cardsUsed]
|
||||
|
||||
/* 근거는 반드시 상대가 제시한 값을 물고 있어야 한다.
|
||||
예전엔 첫 카드에서 marketLow 만 읊어서, 얼마를 제시하든 같은 문장이 나왔다.
|
||||
CONCESSION[0] = 0 이라 부르는 값(ask)까지 앵커로 고정이라, 슬라이더를 움직여도
|
||||
화면이 전혀 반응하지 않는 것처럼 보였다. 값은 고수하되(그게 이 에이전트의 성격이다)
|
||||
무엇에 대한 응수인지는 매번 달라져야 한다. */
|
||||
const gap = offer - ask
|
||||
const reason =
|
||||
cardsUsed > 0
|
||||
? `${won(offer)}원과 저희 기준 사이가 아직 ${won(gap)}원 남았습니다.`
|
||||
: offer >= item.listPrice
|
||||
? `정가 그대로는 검토가 어렵습니다. 같은 사양 인터넷 최저가가 ${won(item.marketLow)}원입니다.`
|
||||
: offer > item.marketLow
|
||||
? `${won(offer)}원은 같은 사양 인터넷 최저가 ${won(item.marketLow)}원보다 ${won(
|
||||
offer - item.marketLow,
|
||||
)}원 높습니다.`
|
||||
: `${won(offer)}원이면 시장 최저가 선까지 내려오셨습니다. 다만 이번 견적 기준까지 ${won(gap)}원 남았습니다.`
|
||||
|
||||
return {
|
||||
outcome: "running",
|
||||
price: ask,
|
||||
text: `${reason} ${won(ask)}원까지 맞춰주시면 ${lever}으로 보전해 드리겠습니다.`,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* buyer 모드 — 사용자가 목표가만 정하면 에이전트가 협력사와 알아서 붙는다.
|
||||
* 전체 턴을 미리 만들어 두고 화면에서 하나씩 재생한다.
|
||||
*/
|
||||
export function simulateBuyerRun(item: DemoItem, target: number): { turns: Turn[]; outcome: Outcome; finalPrice: number } {
|
||||
const turns: Turn[] = []
|
||||
let id = 0
|
||||
const push = (side: Turn["side"], text: string, price?: number) => turns.push({ id: id++, side, text, price })
|
||||
|
||||
push("counterpart", `원자재가 올라서 이번 분기는 ${won(item.listPrice)}원이 최선입니다.`, item.listPrice)
|
||||
|
||||
// 목표가가 앵커보다 낮으면 협력사가 받아들일 수 없는 구간이다.
|
||||
// 에이전트는 기준 밖으로 나가지 않으므로 개찰로 끝난다 — 제품의 안전장치를 보여주는 케이스다.
|
||||
const reachable = target >= item.anchor
|
||||
|
||||
/* 에이전트의 첫 수는 사용자가 준 목표가를 물고 있어야 한다. 예전엔 marketLow 만 읊어서
|
||||
목표가를 얼마로 잡든 같은 문장이 나왔다 — 위임한 기준이 반영되는지 확인할 수가 없었다.
|
||||
여는 말(협력사 정가 제시)은 아직 목표가를 모르는 시점이라 상수로 둔다. */
|
||||
const stance =
|
||||
target < item.marketLow
|
||||
? `시장 최저가보다 낮은 목표라 근거부터 깔겠습니다.`
|
||||
: `시장 최저가 선이라 무리 없이 접근하겠습니다.`
|
||||
push(
|
||||
"agent",
|
||||
`목표가 ${won(target)}원 받았습니다. ${stance} 같은 사양 인터넷 최저가가 ${won(
|
||||
item.marketLow,
|
||||
)}원입니다. 연간 물량을 보증하면 어느 선까지 가능하신가요?`,
|
||||
item.marketLow,
|
||||
)
|
||||
|
||||
const mid = round10((item.listPrice + Math.max(target, item.anchor)) / 2)
|
||||
push("counterpart", `공정상 한 번에 내리긴 어렵고, ${won(mid)}원까지는 조정하겠습니다.`, mid)
|
||||
|
||||
if (!reachable) {
|
||||
push(
|
||||
"agent",
|
||||
`목표가 ${won(target)}원은 협력사가 받아들일 수 있는 선 아래입니다. 무리하게 밀지 않고 이 건은 개찰로 마감하겠습니다.`,
|
||||
mid,
|
||||
)
|
||||
return { turns, outcome: "open", finalPrice: mid }
|
||||
}
|
||||
|
||||
push("agent", `${won(target)}원이면 연 12회 정기 발주로 확정하겠습니다. 대신 납기는 2주 여유를 드리겠습니다.`, target)
|
||||
push("counterpart", `정기 발주와 결제 조건을 지켜주신다면 ${won(target)}원으로 맞추겠습니다.`, target)
|
||||
push(
|
||||
"agent",
|
||||
`${won(target)}원으로 확정했습니다. 최초 제시가 대비 ${won(item.listPrice - target)}원 절감입니다.`,
|
||||
target,
|
||||
)
|
||||
|
||||
return { turns, outcome: "award", finalPrice: target }
|
||||
}
|
||||
|
||||
/** 절감액·절감률. 결과 화면과 상담 신청 연결에 쓴다. */
|
||||
export function savings(item: DemoItem, finalPrice: number) {
|
||||
const amount = Math.max(0, item.listPrice - finalPrice)
|
||||
return { amount, rate: (amount / item.listPrice) * 100 }
|
||||
}
|
||||
@@ -8,6 +8,9 @@ export const links: Route.LinksFunction = () => [
|
||||
{ rel: "icon", href: "/favicon.svg", type: "image/svg+xml" },
|
||||
// 본문 서체 프리로드 — 프리렌더된 첫 화면의 FOUT 최소화
|
||||
{ rel: "preload", href: "/fonts/PretendardVariable.woff2", as: "font", type: "font/woff2", crossOrigin: "anonymous" },
|
||||
/* 영문 디스플레이 서체는 self-host 한다(latin 서브셋 39KB).
|
||||
구글 폰트 CDN 을 쓰면 서드파티 요청이 LCP 를 흔들고 방문자 IP 가 외부로 나간다.
|
||||
preload 는 걸지 않는다 — 라벨 전용이라 폴드 위 렌더를 막을 이유가 없다. */
|
||||
];
|
||||
|
||||
export function Layout({ children }: { children: ReactNode }) {
|
||||
|
||||
@@ -5,14 +5,16 @@ import { Faq } from "@/components/sections/faq";
|
||||
import { FinalCTA } from "@/components/sections/final-cta";
|
||||
import { Footer } from "@/components/sections/footer";
|
||||
import { Header } from "@/components/sections/header";
|
||||
import { HeroNeumorphic } from "@/components/sections/hero-neumorphic";
|
||||
import { HeroDataFlow } from "@/components/sections/hero-dataflow";
|
||||
import { HowItWorksDemo } from "@/components/sections/how-it-works-demo";
|
||||
import { NegotiationConsole } from "@/components/sections/negotiation-console";
|
||||
import { NegotiationDemo } from "@/components/sections/negotiation-demo";
|
||||
import { Reinforcement } from "@/components/sections/reinforcement";
|
||||
|
||||
const TITLE = "negotium — AI 구매 협상 자동화";
|
||||
/* 한글·영문을 둘 다 담는다. 본문은 "네고시움"으로 갔지만 타이틀에서 영문을 빼면
|
||||
"negotium" 으로 검색해 들어오던 유입이 끊긴다 — 검색 질의는 사용자가 정하지 우리가 못 정한다. */
|
||||
const TITLE = "네고시움(negotium) — AI 구매 협상 자동화";
|
||||
const DESCRIPTION =
|
||||
"가이드라인만 정하면 AI 흥정 봇이 여러 협력사와 단가를 대신 조율합니다. 흥정부터 낙찰까지 자동으로, 협상할수록 강화학습으로 더 좋은 조건을 만드는 B2B 구매 협상 자동화 솔루션.";
|
||||
"품목·목표가·마감일만 정하면 협상 에이전트가 협력사마다 1:1로 단가를 조율하고 낙찰까지 판정합니다. 협상 기록이 쌓일수록 조건이 좋아지는 B2B 구매 협상 자동화 솔루션.";
|
||||
|
||||
export function meta() {
|
||||
return [
|
||||
@@ -30,8 +32,8 @@ export default function Home() {
|
||||
return (
|
||||
<div className="min-h-screen bg-white text-ink font-sans antialiased selection:bg-primary/10 selection:text-primary">
|
||||
<Header />
|
||||
<HeroNeumorphic />
|
||||
<NegotiationConsole />
|
||||
<HeroDataFlow />
|
||||
<NegotiationDemo />
|
||||
<HowItWorksDemo />
|
||||
<Reinforcement />
|
||||
<CoreValues />
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# 히어로 CTA 문구 변경 결정 기록
|
||||
|
||||
- **일자**: 2026-08-07
|
||||
- **상태**: 적용·배포 완료
|
||||
- **범위**: 히어로 CTA 2종, 데모 요청 모달 제목
|
||||
- **관련 커밋**: `77d96cd`
|
||||
|
||||
---
|
||||
|
||||
## 요약
|
||||
|
||||
히어로 상단 CTA 2종의 문구를 변경했다. 최초 지시안을 검토 과정에서 일부 수정했으며,
|
||||
수정안으로 승인·적용·배포를 완료했다.
|
||||
|
||||
## 1. 변경 내역
|
||||
|
||||
| 위치 | 기존 | 최초 지시안 | **최종 적용** |
|
||||
|---|---|---|---|
|
||||
| 1차 CTA | 여기서 직접 체험 | 협상 예시 보기 | **협상 예시 체험** |
|
||||
| 2차 CTA | 데모 요청 | 직접 체험 | **실제 데모 받기** |
|
||||
| 모달 제목 | 데모 요청 | (미지정) | **실제 데모 받기** |
|
||||
|
||||
## 2. 최초 지시안을 수정한 사유
|
||||
|
||||
두 버튼은 클릭 후 경험이 전혀 다르다. 1차는 페이지 내에서 즉시 조작하는 인터랙티브
|
||||
데모(`#how-it-works`)이고, 2차는 이름·이메일을 받는 리드 수집 폼(모달)이다.
|
||||
|
||||
| 지시안 | 확인된 문제 | 사업적 영향 |
|
||||
|---|---|---|
|
||||
| 협상 예시 **보기** | 도착 섹션이 "직접 경험해 보세요", 역할 카드가 "공급사로 해보기"로 조작을 요구함. 버튼은 관람을 약속하고 목적지는 참여를 요구 | 클릭 전 기대와 실제 요구 불일치 → 데모 진입 단계 이탈 |
|
||||
| **직접 체험** | 클릭 시 실제로는 입력 폼이 노출됨. 체험은 이메일 수신 이후 시작 | 즉시 체험을 기대한 방문자의 신뢰 저하 → 리드 폼 이탈 |
|
||||
|
||||
## 3. 최종안이 지시 의도를 유지하는 방식
|
||||
|
||||
최초 지시의 핵심 의도는 **"페이지 내 데모는 시뮬레이션, 이메일 데모가 실제 제품"**
|
||||
이라는 구분이었으며, 최종안은 이를 그대로 반영했다.
|
||||
|
||||
| 요소 | 반영 방식 |
|
||||
|---|---|
|
||||
| 시뮬레이션임을 명시 | "**예시**" 유지 — 고정 데이터 기반임을 표기 |
|
||||
| 목적지와의 정합성 | "**체험**" 유지 — 섹션 헤드라인·역할 카드와 충돌 없음 |
|
||||
| 실제 제품 구분 | "**실제** 데모" — 온페이지 예시와 명확히 분리 |
|
||||
| 전달 경로 명시 | "**받기**" — 이메일 수신 방식임이 드러나 폼 노출이 자연스러움 |
|
||||
|
||||
## 4. 부수 조치
|
||||
|
||||
| 항목 | 조치 | 사유 |
|
||||
|---|---|---|
|
||||
| 모달 제목 | "데모 요청" → "실제 데모 받기" | 버튼과 창 제목 불일치 시 전환 순간 이탈 방지 |
|
||||
| 모달 제출 버튼 | "데모 신청" **유지** | 해당 클릭의 실제 결과는 신청 접수이며, 데모 수령은 이메일 단계에서 발생 |
|
||||
| 데모 섹션 헤드라인 | **변경 없음** | 최종안이 "체험"을 유지하여 수정 불필요 |
|
||||
|
||||
## 5. 적용 원칙
|
||||
|
||||
> **버튼 문구는 클릭 시 실제로 발생하는 동작을 기술한다.**
|
||||
> 문구와 동작이 어긋나면 전환 손실로 직결된다.
|
||||
|
||||
이 원칙은 이후 CTA 문구를 손볼 때 같은 기준으로 적용한다. 특히 아래 두 경우를 주의한다.
|
||||
|
||||
- **목적지와 동사가 어긋나는 경우** — 버튼이 "보기"인데 도착지가 조작을 요구하면 안 된다.
|
||||
- **폼을 여는 버튼에 결과를 약속하는 경우** — "체험"·"시작" 류는 즉시 그 일이 일어날 때만 쓴다.
|
||||
|
||||
## 6. 참고 — 관련 코드 위치
|
||||
|
||||
| 대상 | 파일 |
|
||||
|---|---|
|
||||
| 히어로 CTA 2종 | `app/components/sections/hero-dataflow.tsx` |
|
||||
| 모달 제목·제출 버튼 | `app/components/ui/demo-request-modal.tsx` |
|
||||
| 도착 섹션 헤드라인·역할 카드 | `app/components/sections/negotiation-demo.tsx` |
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* 리드 수신용 Google Apps Script — 데모 요청·상담 신청을 스프레드시트에 적재한다.
|
||||
*
|
||||
* 이 파일은 랜딩 번들에 포함되지 않는다. Google Apps Script 편집기에 붙여넣을 원본이고,
|
||||
* 여기 두는 이유는 배포 후 이 코드가 어디에도 남지 않으면 나중에 아무도 손댈 수 없기 때문이다.
|
||||
*
|
||||
* ── 설치 (약 3분) ────────────────────────────────────────────────────────────
|
||||
* 1. 새 Google 스프레드시트를 만든다. 시트 이름은 그대로 둬도 된다.
|
||||
* 2. 확장 프로그램 → Apps Script → 기본 코드를 지우고 이 파일 전체를 붙여넣는다.
|
||||
* 3. 배포 → 새 배포 → 유형 "웹 앱"
|
||||
* 실행 계정 : 나
|
||||
* 액세스 권한 : 모든 사용자 ← 이걸 "나"로 두면 랜딩에서 호출이 막힌다
|
||||
* 4. 배포하면 나오는 URL(https://script.google.com/macros/s/…/exec)을 복사한다.
|
||||
* 5. Vercel → negotium-landing → Settings → Environment Variables 에
|
||||
* 이름 LEAD_WEBHOOK_URL / 값 복사한 URL / Production 체크
|
||||
* 6. 다시 배포한다. 환경변수는 배포 시점에 주입되므로 재배포 전에는 적용되지 않는다.
|
||||
*
|
||||
* ── 동작 ────────────────────────────────────────────────────────────────────
|
||||
* api/lead.ts 가 아래 형태로 POST 한다. 필드가 늘어도 헤더를 자동으로 확장하므로
|
||||
* 이 스크립트를 다시 고칠 일은 거의 없다.
|
||||
* { text, source, name, email, company, phone, message, submittedAt, userAgent }
|
||||
*
|
||||
* 주의: 웹 앱은 POST 에 302 를 돌려주고 script.googleusercontent.com 으로 넘긴다.
|
||||
* api/lead.ts 의 fetch 는 리다이렉트를 따라가므로 최종 200 을 받는다 — 정상이다.
|
||||
*/
|
||||
|
||||
/** 리드가 쌓일 시트 이름. 없으면 자동 생성한다. */
|
||||
var SHEET_NAME = 'leads'
|
||||
|
||||
/** 항상 이 순서로 왼쪽부터 채운다. 나머지 필드는 뒤에 자동으로 붙는다. */
|
||||
var PREFERRED = ['submittedAt', 'source', 'name', 'email', 'company', 'phone', 'message', 'userAgent']
|
||||
|
||||
function doPost(e) {
|
||||
try {
|
||||
var payload = JSON.parse((e && e.postData && e.postData.contents) || '{}')
|
||||
|
||||
// text 는 Slack 전용 요약이라 시트에는 넣지 않는다. 같은 내용이 개별 필드에 이미 있다.
|
||||
delete payload.text
|
||||
|
||||
var lock = LockService.getScriptLock()
|
||||
lock.waitLock(20000) // 동시 제출이 같은 행에 겹쳐 쓰는 것을 막는다
|
||||
try {
|
||||
var sheet = getSheet_()
|
||||
var header = ensureHeader_(sheet, payload)
|
||||
var row = header.map(function (key) {
|
||||
return payload[key] === undefined ? '' : payload[key]
|
||||
})
|
||||
sheet.appendRow(row)
|
||||
} finally {
|
||||
lock.releaseLock()
|
||||
}
|
||||
|
||||
return json_({ ok: true })
|
||||
} catch (err) {
|
||||
// 실패해도 랜딩 쪽 api/lead.ts 가 이미 로그를 남겼으므로 리드 자체는 보존된다.
|
||||
return json_({ ok: false, error: String(err) })
|
||||
}
|
||||
}
|
||||
|
||||
/** 브라우저로 URL 을 열었을 때 살아있는지 확인용. 배포 직후 점검에 쓴다. */
|
||||
function doGet() {
|
||||
return json_({ ok: true, service: 'negotium lead sink' })
|
||||
}
|
||||
|
||||
function getSheet_() {
|
||||
var ss = SpreadsheetApp.getActiveSpreadsheet()
|
||||
return ss.getSheetByName(SHEET_NAME) || ss.insertSheet(SHEET_NAME)
|
||||
}
|
||||
|
||||
/** 헤더가 없으면 만들고, 처음 보는 필드가 오면 열을 덧붙인다. */
|
||||
function ensureHeader_(sheet, payload) {
|
||||
var lastCol = sheet.getLastColumn()
|
||||
var header = lastCol ? sheet.getRange(1, 1, 1, lastCol).getValues()[0].filter(String) : []
|
||||
|
||||
if (!header.length) {
|
||||
header = PREFERRED.filter(function (k) {
|
||||
return k in payload
|
||||
})
|
||||
Object.keys(payload).forEach(function (k) {
|
||||
if (header.indexOf(k) === -1) header.push(k)
|
||||
})
|
||||
sheet.getRange(1, 1, 1, header.length).setValues([header]).setFontWeight('bold')
|
||||
sheet.setFrozenRows(1)
|
||||
return header
|
||||
}
|
||||
|
||||
var added = Object.keys(payload).filter(function (k) {
|
||||
return header.indexOf(k) === -1
|
||||
})
|
||||
if (added.length) {
|
||||
sheet.getRange(1, header.length + 1, 1, added.length).setValues([added]).setFontWeight('bold')
|
||||
header = header.concat(added)
|
||||
}
|
||||
return header
|
||||
}
|
||||
|
||||
function json_(obj) {
|
||||
return ContentService.createTextOutput(JSON.stringify(obj)).setMimeType(ContentService.MimeType.JSON)
|
||||
}
|
||||
Generated
+2359
-63
File diff suppressed because it is too large.
Load diff
@@ -13,13 +13,13 @@
|
||||
"@react-router/node": "^7.17.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"isbot": "^5",
|
||||
"lucide-react": "^0.546.0",
|
||||
"motion": "^12.23.24",
|
||||
"react": "^19.0.1",
|
||||
"react-dom": "^19.0.1",
|
||||
"react-router": "^7.17.0",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"isbot": "^5"
|
||||
"tailwind-merge": "^3.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@react-router/dev": "^7.17.0",
|
||||
@@ -27,6 +27,7 @@
|
||||
"@types/node": "^22.14.0",
|
||||
"@types/react": "^19.0.1",
|
||||
"@types/react-dom": "^19.0.1",
|
||||
"@vercel/node": "^5.9.5",
|
||||
"tailwindcss": "^4.1.14",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^6.2.3"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 98 KiB |
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||
"framework": null,
|
||||
"buildCommand": "npm run build",
|
||||
"outputDirectory": "build/client",
|
||||
"rewrites": [{ "source": "/((?!api/).*)", "destination": "/index.html" }]
|
||||
}
|
||||
Loaded 100 of 319 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user