[feat] negosium·negodata: 협상 거부 흐름 정리 + 오프라인 계약가 낙찰 + 견적 상세 리모델링

협상 불가 사유를 내면 500 이 나고, 거부 폼은 목록·채팅이 따로 놀았으며,
제출한 내용을 다시 볼 방법이 없었다. 결렬 건은 협력사가 낸 거부가를 계약가로
간주해 낙찰시켜 절감 통계가 음수로 뒤집힐 수 있었고, 견적 상세는 판정 가격이
세 곳에 흩어져 대화 탭에선 아예 보이지 않았다.

agent
- 결렬 종료 로깅 크래시 수정 — _log 를 action_id 기반으로 되돌리고 선택 근거
  (Q·UCB·방문수)는 decision/policy 가 있을 때만 채운다. 종료 행은 카드 선택이
  없고 policy.update 뒤라 값을 넣으면 학습 화면 집계가 오염된다

negosium
- 거부 폼을 목록·채팅 공용 컴포넌트 하나로 통일(사유 3종 + 공급 희망가·의견 선택)
- 거부 사유 열람 — 목록에 '거부 사유 보기'(부가정보 보기와 같은 규격), 채팅
  재진입 시 대화 끝에 거부 내역 카드. 목록·채팅 init 응답에 reject_reason·reject_price 추가
- 자유 입력 거부("협상 포기합니다")가 사유 NULL 로 저장되던 문제 수정 — 폼 마커가
  없으면 원문을 사유로 쓰고, 문장 속 숫자를 희망가로 오인하지 않는다
- koreanNumber 를 전역 lib 으로 이동(공용 폼이 쓴다)

negodata
- 직접 낙찰에 계약가 입력 — 결렬·미응찰 건을 오프라인으로 다시 협상한 결과를
  담당자가 확정해 넣는다. 후보는 초청 협력사 전부(가격 미제출도 포함),
  계약가는 sessions.custom.offline_award 에 근거·작성자·시각과 함께 남긴다
- 통계 계약가 = 담당자 확정가 우선, 없으면 투찰가. 거부가를 계약가로 치던 파생 제거.
  KPI 에 오프라인 반영 건수 추가
- 견적 상세 리모델링 — 가격 레일(앵커링가/투찰현황 · 목표가 · 타결 상한가 · 결과가)을
  시트에 고정해 접힘·탭 전환에도 남기고, 스펙트럼에 타결 판정선과 구간색 추가.
  라벨은 폭을 실측해 두 레인으로 배치(겹침 불가). 상품·마감시각 등 전 행 동일 컬럼 제거,
  협상현황에 부가정보 노출, 1:1 은 협력사·세션상태를 결과 밴드로 올림

테스트: negosium 58 · negodata 110 통과. 프론트 빌드/린트 통과.
This commit is contained in:
minaChoi committed 2026-08-12 10:25:26 +09:00
1 parent d02ba20520
commit 6eb4dc26f8
70 files changed
+1695 -739

No files matched your search

@@ -7,6 +7,9 @@
import type { CardUsageRowName } from './cardUsageRowName';
import type { CardUsageRowCardId } from './cardUsageRowCardId';
import type { CardUsageRowLastUsedAt } from './cardUsageRowLastUsedAt';
import type { CardUsageRowAvgQ } from './cardUsageRowAvgQ';
import type { CardUsageRowAvgUcb } from './cardUsageRowAvgUcb';
import type { CardUsageRowExploreBonus } from './cardUsageRowExploreBonus';
export interface CardUsageRow {
number: string;
@@ -18,4 +21,8 @@ export interface CardUsageRow {
share?: number;
avg_turn?: number;
last_used_at?: CardUsageRowLastUsedAt;
avg_q?: CardUsageRowAvgQ;
avg_ucb?: CardUsageRowAvgUcb;
explore_bonus?: CardUsageRowExploreBonus;
visits?: number;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type CardUsageRowAvgQ = number | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type CardUsageRowAvgUcb = number | null;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type CardUsageRowExploreBonus = number | null;
@@ -25,7 +25,10 @@ export * from './cardDataUserId';
export * from './cardStatus';
export * from './cardType';
export * from './cardUsageRow';
export * from './cardUsageRowAvgQ';
export * from './cardUsageRowAvgUcb';
export * from './cardUsageRowCardId';
export * from './cardUsageRowExploreBonus';
export * from './cardUsageRowLastUsedAt';
export * from './cardUsageRowName';
export * from './cardUsageType';
@@ -159,6 +162,7 @@ export * from './renegotiationDataNextQuotationId';
export * from './renegotiationDataTargetPrice';
export * from './reqApproveRenegotiation';
export * from './reqAwardQuotation';
export * from './reqAwardQuotationContractNote';
export * from './reqBulkMapByNames';
export * from './reqCheckCodes';
export * from './reqCreateCard';
@@ -432,6 +436,7 @@ export * from './sessionDataBidAt';
export * from './sessionDataBidPrice';
export * from './sessionDataCustom';
export * from './sessionDataCustomAnyOf';
export * from './sessionDataDoneCeilingPrice';
export * from './sessionDataEmailSentAt';
export * from './sessionDataRejectDeliveryType';
export * from './sessionDataRejectPrice';
@@ -4,7 +4,10 @@
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
import type { ReqAwardQuotationContractNote } from './reqAwardQuotationContractNote';
export interface ReqAwardQuotation {
winner_supplier_id: string;
contract_price: number;
contract_note?: ReqAwardQuotationContractNote;
}
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type ReqAwardQuotationContractNote = string | null;
@@ -6,6 +6,7 @@
*/
import type { QuotationType } from './quotationType';
import type { SessionDataAnchoringPrice } from './sessionDataAnchoringPrice';
import type { SessionDataDoneCeilingPrice } from './sessionDataDoneCeilingPrice';
import type { SessionStatus } from './sessionStatus';
import type { SessionDataBidPrice } from './sessionDataBidPrice';
import type { SessionDataBidAt } from './sessionDataBidAt';
@@ -25,6 +26,7 @@ export interface SessionData {
qt_type: QuotationType;
target_price: number;
anchoring_price?: SessionDataAnchoringPrice;
done_ceiling_price?: SessionDataDoneCeilingPrice;
status: SessionStatus;
bid_price?: SessionDataBidPrice;
bid_at?: SessionDataBidAt;
@@ -0,0 +1,8 @@
/**
* Generated by orval v7.21.0 🍺
* Do not edit manually.
* Negodata Api Server
* OpenAPI spec version: 0.1.0
*/
export type SessionDataDoneCeilingPrice = number | null;
@@ -14,4 +14,5 @@ export interface StatKpi {
closed_count?: number;
regen_avg_round?: number;
markup_suppression_rate?: number;
offline_award_count?: number;
}
@@ -57,6 +57,15 @@ export function CardLearningView({ data }: { data: LearningData }) {
<TableHead className="w-32 text-right">
<HeadWithHelp label="평균 라운드" help="이 카드가 협상의 몇 번째 라운드에 나갔는지의 평균입니다. 값이 작으면 초반에, 크면 종결 무렵에 나간다는 뜻입니다. 종결 전용으로 설정한 카드가 초반에 나오고 있지는 않은지 확인할 때 봅니다." />
</TableHead>
<TableHead className="w-28 text-right">
<HeadWithHelp label="Q값" help="강화학습이 이 카드에 매긴 값어치입니다(선택 시점 평균). 높을수록 이 국면에서 성과가 좋았다고 학습된 카드입니다. 봇은 Q값에 탐색 보너스를 더한 점수가 가장 높은 카드를 고릅니다." />
</TableHead>
<TableHead className="w-28 text-right">
<HeadWithHelp label="탐색 보너스" help="아직 덜 써봐서 붙는 가산점입니다(UCB − Q). 이 값이 Q값보다 크면 성과가 좋아서가 아니라 '아직 검증이 덜 돼서' 뽑힌 것입니다. 방문수가 쌓이면 0에 수렴합니다." />
</TableHead>
<TableHead className="w-24 text-right">
<HeadWithHelp label="방문수" help="이 카드가 학습에서 선택된 누적 횟수입니다. 적으면 Q값이 아직 추측에 가깝고, 많을수록 검증된 값입니다." />
</TableHead>
<TableHead className="w-36 text-right">마지막 사용</TableHead>
</TableRow>
</TableHeader>
@@ -84,6 +93,9 @@ export function CardLearningView({ data }: { data: LearningData }) {
<TableCell className="text-right">{c.uses}</TableCell>
<TableCell className="text-right">{pct(c.share)}</TableCell>
<TableCell className="text-right">{c.avgTurn ? `${c.avgTurn}R` : '-'}</TableCell>
<TableCell className="text-right font-mono">{num4(c.avgQ)}</TableCell>
<TableCell className="text-right font-mono text-muted-foreground">{num4(c.exploreBonus)}</TableCell>
<TableCell className="text-right">{c.visits || '-'}</TableCell>
<TableCell className="text-right text-muted-foreground">
{c.lastUsedAt ? fmtDateTime(c.lastUsedAt) : '-'}
</TableCell>
@@ -286,6 +298,11 @@ function pct(v: number): string {
return `${(v * 100).toFixed(0)}%`;
}
// Q값·탐색 보너스는 0에 가까운 소수라 반올림하면 차이가 사라진다 — 네 자리까지 그대로 보여준다.
function num4(v: number | null): string {
return v == null ? '-' : v.toFixed(4);
}
// 앵커링 값은 천분율(‰)로 저장된다 — 10 = 1%. 화면은 담당자가 쓰는 단위(%)로 보여준다.
function rate(v: number): string {
return `${(v / 10).toFixed(1)}%`;
@@ -24,6 +24,9 @@ export function useLearningData(): { data: LearningData; isLoading: boolean } {
share: c.share ?? 0,
avgTurn: c.avg_turn ?? 0,
lastUsedAt: c.last_used_at ?? null,
avgQ: c.avg_q ?? null,
exploreBonus: c.explore_bonus ?? null,
visits: c.visits ?? 0,
})),
},
};
@@ -10,6 +10,10 @@ export type CardRow = {
share: number; // 전체 카드 사용 중 비중
avgTurn: number; // 평균 몇 번째 라운드에 나갔는지
lastUsedAt: string | null;
// 선택 근거 — 봇은 UCB(=Q + 탐색보너스)가 가장 높은 카드를 고른다.
avgQ: number | null; // 선택 시점 Q값 평균
exploreBonus: number | null; // UCB - Q. 클수록 '아직 덜 검증돼서' 뽑힌 것
visits: number; // 마지막 선택 시점 누적 방문수
};
export type LearningData = {
@@ -0,0 +1,116 @@
import { useState } from 'react';
import { X, Gavel, Loader2 } from 'lucide-react';
import { useScrollLock } from '@/lib/useScrollLock';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Typography } from '@/components/ui/typography';
import { SessionStatus } from '@/api/generated/model';
import { awardPrice, sessionStatusLabel, type SessionView } from '../../types';
type AwardModalProps = {
open: boolean;
/** 낙찰시킬 협력사의 세션 — 마지막 제출가를 계약가 기본값으로 쓴다. */
winner: SessionView;
/** 확정 → 직접 낙찰 호출. 성공(true) 시 모달 닫힘. */
onConfirm: (contractPrice: number, contractNote: string) => Promise<boolean>;
onClose: () => void;
};
// 개찰 견적의 직접 낙찰 모달.
// 결렬·미응찰 건은 오프라인으로 다시 협상하고 그 결과를 여기에 반영한다 — 그래서 계약가는
// 시스템 제출가를 기본값으로 채워두되 담당자가 고쳐 넣을 수 있고, 근거를 메모로 남긴다.
export function AwardModal({ open, winner, onConfirm, onClose }: AwardModalProps) {
const submitted = awardPrice(winner);
const [price, setPrice] = useState<string>(submitted != null ? String(submitted) : '');
const [note, setNote] = useState('');
const [saving, setSaving] = useState(false);
useScrollLock(open);
if (!open) return null;
const parsed = Number(price.replace(/[^0-9]/g, ''));
const canSubmit = parsed > 0 && !saving;
const changed = submitted != null && parsed > 0 && parsed !== submitted;
const handleConfirm = async () => {
if (!canSubmit) return;
setSaving(true);
try {
const ok = await onConfirm(parsed, note.trim());
if (ok) onClose();
} finally {
setSaving(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
<div className="w-full max-w-md overflow-hidden rounded-xl border border-border bg-background shadow-xl">
<div className="flex items-start justify-between border-b border-border p-5">
<div className="min-w-0">
<Typography variant="h4" className="flex items-center gap-2">
<Gavel className="size-4 text-primary" />
직접 낙찰
</Typography>
<Typography variant="muted" className="mt-1 truncate">
{winner.supplier_name} · {sessionStatusLabel(winner.status)}
</Typography>
</div>
<button type="button" onClick={onClose} aria-label="닫기" className="rounded-md p-1 hover:bg-muted">
<X className="size-4" />
</button>
</div>
<div className="space-y-4 p-5">
<div className="space-y-1.5">
<Typography variant="small" className="font-semibold">
계약가
</Typography>
<Input
inputMode="numeric"
value={parsed ? parsed.toLocaleString() : ''}
onChange={(e) => setPrice(e.target.value)}
placeholder="예: 12,800,000"
autoFocus
/>
<Typography variant="muted">
{submitted != null
? `협력사 제출가 ₩${submitted.toLocaleString()}${changed ? ' — 오프라인 협상으로 바뀐 금액을 넣었습니다.' : ''}`
: winner.status === SessionStatus.NOT_PARTICIPATED
? '이 협력사는 협상에 참여하지 않았습니다 — 오프라인 합의가를 직접 넣어 주세요.'
: '제출한 가격이 없습니다 — 오프라인 합의가를 직접 넣어 주세요.'}
</Typography>
</div>
<div className="space-y-1.5">
<Typography variant="small" className="font-semibold">
계약 근거 <span className="font-normal text-muted-foreground">(선택)</span>
</Typography>
<textarea
value={note}
onChange={(e) => setNote(e.target.value)}
rows={3}
maxLength={255}
className="w-full resize-none rounded border border-border bg-background p-2 text-xs"
placeholder="예: 오프라인 협상 결과, 8/12 통화로 단가 합의"
/>
</div>
<Typography variant="muted">
낙찰은 되돌릴 수 없습니다. 계약가는 통계의 절감액 기준이 됩니다.
</Typography>
</div>
<div className="flex justify-end gap-2 border-t border-border p-4">
<Button variant="outline" onClick={onClose} disabled={saving}>
취소
</Button>
<Button onClick={handleConfirm} disabled={!canSubmit}>
{saving && <Loader2 className="size-4 animate-spin" />}
낙찰 확정
</Button>
</div>
</div>
</div>
);
}
@@ -7,12 +7,14 @@ import { typographyVariants } from '@/components/ui/typography';
import { InfoField } from './InfoField';
import { QuotationStatusBadge } from './StatusPill';
import { ResultSummaryBand } from './ResultSummaryBand';
import { PriceRail } from './PriceRail';
import type { QuotationData } from '@/api/generated/model/quotationData';
import { useLabels, useHiddenFields } from '@/features/settings/useCompanySettings';
import {
type Product,
type QuotationSetting,
type SessionView,
buildPriceRail,
quotationTypeLabel,
awardCriterionLabel,
fmtDateTime,
@@ -33,14 +35,12 @@ function SectionCard({ title, children }: { title: string; children: ReactNode }
type DrawerHeaderCardsProps = {
quotation: QuotationData;
quotationSettings: QuotationSetting[];
/** 협상 세션 뷰 — 결과 밴드가 낙찰가/절감 계산에 쓴다. */
/** 협상 세션 뷰 — 가격 레일과 결과 밴드가 기준가/낙찰가 계산에 쓴다. */
sessionViews: SessionView[];
/** 현재 선택 세션의 상품(없으면 상품 카드는 빈 상태). */
currentProduct: Product | undefined;
/** 목표가 클릭 → 산정내역 모달(대표 세션 기준). 목표가/앵커링가는 견적 단위(1견적=1상품)라 세션 공통값. */
/** 목표가 클릭 → 산정내역 모달(대표 세션 기준). 목표가는 견적 단위(1견적=1상품)라 세션 공통값. */
onShowTarget: (sessionId: string) => void;
/** 접힘 상태 — 상세 그리드는 감추고 상단 결과 요약(목표가·낙찰·절감) 밴드만 남긴다. */
collapsed?: boolean;
};
export function DrawerHeaderCards({
@@ -49,39 +49,23 @@ export function DrawerHeaderCards({
sessionViews,
currentProduct,
onShowTarget,
collapsed = false,
}: DrawerHeaderCardsProps) {
const label = useLabels(); // 회사 설정 용어(목표 마진 등)
const isHidden = useHiddenFields(); // 회사설정으로 감춘 가격 필드는 상품 카드에서도 제외
// 접으면 결과 요약 밴드만 노출(목표가·낙찰·절감). 상세 그리드 계산은 건너뛴다.
if (collapsed) {
return (
<div className="text-xs font-mono">
<ResultSummaryBand quotation={quotation} sessionViews={sessionViews} />
</div>
);
}
// Quotations DDL 표시값
const q_name = quotation.name || '-';
const q_number = quotation.number || '-';
const q_round = quotation.round || 1;
const selectedSettingObj = quotationSettings.find((qs) => qs.qt_setting_id === quotation.qt_setting_id);
// 타결 상한율(‰) — 견적 override 우선, 없으면 적용 세팅값.
const ceilingRate = quotation.done_ceiling_rate ?? selectedSettingObj?.done_ceiling_rate ?? 50;
const won = (n?: number | null) => (n != null ? `₩${Number(n).toLocaleString()}` : '-');
const q_end_time = quotation.end_time ? fmtDateTime(quotation.end_time) : '-';
const q_created_at = fmtDateTime(quotation.created_at);
const q_manager =
quotation.manager_name || quotation.manager_email
? `${quotation.manager_name || '-'} (${quotation.manager_email || '-'})`
: '-';
const q_memo = quotation.memo || '-';
const selectedSettingObj = quotationSettings.find((qs) => qs.qt_setting_id === quotation.qt_setting_id);
// 목표가·앵커링가는 견적 단위값(1견적=1상품 → 모든 세션 공통). 대표 세션 하나에서 읽어 견적 정보에 표기한다.
const repSession = sessionViews[0];
const repSessionId = repSession?.session_id;
// 상품 카드는 '가격 관련' 값만 노출(모델명·규격·제조사 등 스펙은 상품 상세에서 확인).
const won = (n?: number | null) => (n != null ? `₩${Number(n).toLocaleString()}` : '-');
// 상품 카드는 '가격 관련' 값만 노출(모델명·규격 등 스펙은 상품 상세에서).
const productPriceRows = currentProduct
? [
{ key: 'price', label: label('item.price'), value: won(currentProduct.price) },
@@ -92,52 +76,38 @@ export function DrawerHeaderCards({
: [];
return (
<div className="mt-4 space-y-4 text-xs">
{/* 결과 요약: 목표가 대비 낙찰/절감 */}
<ResultSummaryBand quotation={quotation} sessionViews={sessionViews} />
<div className="text-xs">
<div className="space-y-4">
{/* 마감 결과·낙찰 협력사 + 가격 스펙트럼 (금액은 레일이 책임진다) */}
<ResultSummaryBand quotation={quotation} sessionViews={sessionViews} ceilingRate={ceilingRate} />
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* 견적 정보 */}
<SectionCard title="견적 정보">
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 font-mono text-muted-foreground">
<InfoField label="견적명" value={q_name} valueClassName="font-sans" />
<InfoField label="견적번호" value={q_number} />
<InfoField label="유형" value={quotationTypeLabel(quotation.type)} />
<InfoField label="차수" value={`${q_round}차`} />
<InfoField label="낙찰 기준" value={awardCriterionLabel(quotation.type, quotation.mid_action, quotation.over_action)} valueClassName="font-sans" />
<InfoField label="목표가">
{repSessionId ? (
<button
type="button"
onClick={() => onShowTarget(repSessionId)}
title="목표가 산정 내역 보기"
className={cn(typographyVariants({ variant: 'link' }), 'font-bold font-sans')}
>
{won(repSession?.target_price)}
</button>
) : (
<span className="font-sans font-bold text-foreground">{won(repSession?.target_price)}</span>
)}
</InfoField>
<InfoField label="앵커링가" value={won(repSession?.anchoring_price)} valueClassName="font-sans" />
<InfoField label="견적상태" labelClassName="opacity-90 font-bold mb-1">
<QuotationStatusBadge status={quotation.status} />
</InfoField>
<InfoField label="마감시각" value={q_end_time} />
<InfoField label="생성일" value={q_created_at} />
<InfoField label="담당자" value={q_manager} valueClassName="font-sans" />
<InfoField
label="메모"
value={q_memo}
valueClassName="font-sans truncate block"
title={q_memo || ''}
/>
</div>
</SectionCard>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* 견적 정보 — 견적명·번호·차수는 헤더 제목줄에 있어 여기서 반복하지 않는다. */}
<SectionCard title="견적 정보">
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 font-mono text-muted-foreground">
<InfoField label="유형" value={quotationTypeLabel(quotation.type)} valueClassName="font-sans" />
<InfoField
label="낙찰 기준"
value={awardCriterionLabel(quotation.type, quotation.mid_action, quotation.over_action)}
valueClassName="font-sans"
/>
<InfoField label="견적상태" labelClassName="opacity-90 font-bold mb-1">
<QuotationStatusBadge status={quotation.status} />
</InfoField>
<InfoField label="마감시각" value={q_end_time} />
<InfoField label="생성일" value={fmtDateTime(quotation.created_at)} />
<InfoField label="담당자" value={q_manager} valueClassName="font-sans" />
<InfoField
label="메모"
value={q_memo}
valueClassName="font-sans truncate block"
title={q_memo || ''}
/>
</div>
</SectionCard>
{/* 상품 정보(가격) + 견적 세팅 */}
<div className="space-y-4">
<SectionCard title="상품 정보 (가격)">
{/* 상품 가격과 협상 규칙은 함께 읽힌다 — 한 카드로 합친다. */}
<SectionCard title="상품 · 협상 규칙">
{currentProduct ? (
<div className="flex gap-4">
<div className="h-24 w-24 shrink-0 rounded-md border border-border bg-background overflow-hidden flex items-center justify-center">
@@ -169,6 +139,18 @@ export function DrawerHeaderCards({
title={row.value}
/>
))}
{selectedSettingObj ? (
<>
<InfoField
label={label('target_margin')}
value={selectedSettingObj.target_margin}
valueClassName="font-bold text-emerald-600 dark:text-emerald-400 font-sans"
/>
<InfoField label="카드 사용 횟수" value={selectedSettingObj.card_use_count} />
</>
) : (
<InfoField label="견적 세팅" value="미적용" valueClassName="font-sans" />
)}
</div>
</div>
</div>
@@ -176,21 +158,6 @@ export function DrawerHeaderCards({
<div className="text-muted-foreground py-6 text-center">상품 정보가 비어있습니다.</div>
)}
</SectionCard>
<SectionCard title="견적 세팅">
{selectedSettingObj ? (
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 font-mono text-muted-foreground">
<InfoField
label={label('target_margin')}
value={selectedSettingObj.target_margin}
valueClassName="font-bold text-emerald-600 dark:text-emerald-400 font-sans"
/>
<InfoField label="카드 사용 횟수" value={selectedSettingObj.card_use_count} />
</div>
) : (
<div className="text-muted-foreground py-6 text-center">적용된 견적 세팅이 비어있습니다.</div>
)}
</SectionCard>
</div>
</div>
</div>
@@ -0,0 +1,149 @@
import type { ReactNode } from 'react';
import { Typography } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
import type { PriceRailView } from '../../types';
const won = (n?: number | null) => (n != null ? `₩${n.toLocaleString()}` : '-');
/**
* 헤더 가격 레일 — 협상을 판정하는 네 가격을 왼쪽에서 오른쪽 흐름 순으로 고정 노출한다.
* 접힘·대화 탭에서도 남으므로 협상을 보며 기준가를 확인할 수 있다.
*
* 1번 칸만 유형에 따라 갈린다:
* 1:1 = 앵커링가(협력사가 하나라 견적의 값)
* 1:N = 투찰 현황(앵커는 (상품×공급사)마다 달라 대표값이 성립하지 않는다 → 협상현황 표의 협력사별 컬럼으로)
* 4번 칸은 상태로 갈린다: 낙찰가 / 최저 투찰가(개찰) / 현재 제시가·최저가(진행 중).
*/
export function PriceRail({ rail, onShowTarget }: { rail: PriceRailView; onShowTarget?: () => void }) {
const savingsText =
rail.savings != null
? `목표가 대비 ${rail.savings >= 0 ? '−' : '+'}${won(Math.abs(rail.savings))}` +
(rail.savingsRate != null ? ` (${rail.savings >= 0 ? '−' : '+'}${Math.abs(rail.savingsRate * 100).toFixed(1)}%)` : '')
: null;
return (
<div className="grid grid-cols-2 border-b border-border bg-card sm:grid-cols-4">
{rail.oneToOne ? (
<Cell
label="앵커링가"
dot="bg-zinc-400"
value={won(rail.anchorPrice)}
sub={
rail.anchorPrice != null && rail.targetPrice
? `목표가 −${pctGap(rail.targetPrice, rail.anchorPrice)}`
: undefined
}
/>
) : (
<Cell
label="투찰 현황"
dot="bg-zinc-400"
value={`${rail.bidCount} / ${rail.supplierCount}`}
sub="협력사별 앵커링가는 아래 표에서"
/>
)}
<Cell label="목표가" dot="bg-primary" value={won(rail.targetPrice)} onSub={onShowTarget} />
<Cell
label="타결 상한가"
dot="bg-amber-500"
value={won(rail.ceilingPrice)}
valueClassName="text-amber-600 dark:text-amber-400"
sub={`목표가 +${(rail.ceilingRate / 10).toFixed(1)}% · 초과 시 결렬`}
/>
<Cell
label={rail.resultLabel}
badge={rail.resultBadge}
dot={rail.outcome === 'awarded' ? 'bg-emerald-500' : 'bg-amber-500'}
value={rail.resultPrice != null ? won(rail.resultPrice) : '미응찰'}
valueClassName={
rail.resultPrice == null
? 'text-muted-foreground'
: rail.outcome === 'awarded'
? 'text-emerald-600 dark:text-emerald-400'
: 'text-amber-600 dark:text-amber-400'
}
className={rail.outcome === 'awarded' ? 'bg-emerald-50/60 dark:bg-emerald-950/20' : undefined}
sub={savingsText ?? undefined}
/>
</div>
);
}
/** 목표가 대비 하락폭(%) — 앵커가 목표가보다 낮은 정상 케이스만 의미가 있다. */
function pctGap(target: number, anchor: number): string {
if (!target) return '0.0%';
return `${(((target - anchor) / target) * 100).toFixed(1)}%`;
}
function Cell({
label,
badge,
dot,
value,
sub,
onSub,
className,
valueClassName,
}: {
label: string;
badge?: string | null;
dot: string;
value: ReactNode;
sub?: string;
/** 있으면 보조줄이 버튼(목표가 산정 내역) */
onSub?: () => void;
className?: string;
valueClassName?: string;
}) {
return (
<div
className={cn(
'min-w-0 border-r border-border px-4 py-2.5 last:border-r-0',
// 2열(모바일)에서는 윗줄에만 밑줄을 긋고 2번째 칸의 오른쪽 선을 지운다.
// 컨테이너가 이미 아래 테두리를 가지므로 아랫줄에 또 그으면 선이 겹쳐 두꺼워진다.
'[&:nth-child(-n+2)]:border-b sm:[&:nth-child(-n+2)]:border-b-0',
'[&:nth-child(2)]:border-r-0 sm:[&:nth-child(2)]:border-r',
className,
)}
>
<div className="mb-0.5 flex items-center gap-1.5">
<span className={cn('size-1.5 shrink-0 rounded-full', dot)} />
<Typography as="span" variant="caption" className="text-[10.5px] leading-tight">
{label}
</Typography>
{badge && (
<span className="rounded-full bg-amber-100 px-1.5 py-px text-[9.5px] font-bold text-amber-700 dark:bg-amber-950/50 dark:text-amber-400">
{badge}
</span>
)}
</div>
<Typography
as="p"
variant="small"
className={cn('truncate font-mono text-[15px] font-bold tabular-nums tracking-tight text-foreground', valueClassName)}
>
{value}
</Typography>
{/* 보조줄은 값이 없어도 자리를 지킨다 — 칸마다 높이가 달라지면 레일 바닥이 들쭉날쭉해진다. */}
<div className="min-h-[16px] leading-4">
{onSub ? (
<button
type="button"
onClick={onSub}
title="목표가 산정 내역 보기"
className="cursor-pointer text-[10.5px] text-primary hover:underline"
>
산정 내역 보기 ›
</button>
) : sub ? (
<Typography as="p" variant="caption" className="truncate text-[10.5px] tabular-nums">
{sub}
</Typography>
) : null}
</div>
</div>
);
}
@@ -1,152 +1,228 @@
import { Fragment } from 'react';
import { useLayoutEffect, useRef, useState } from 'react';
import { Typography } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
const won = (n?: number | null) => (n != null ? `₩${n.toLocaleString()}` : '-');
const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));
type Tone = 'amber' | 'emerald' | 'zinc';
const TONE_DOT: Record<Tone, string> = {
amber: 'bg-amber-500',
emerald: 'bg-emerald-500',
zinc: 'bg-zinc-400',
};
const TONE_TEXT: Record<Tone, string> = {
amber: 'text-amber-600',
emerald: 'text-emerald-600',
zinc: 'text-muted-foreground',
};
/** 라벨 사이 최소 간격(px). 이보다 가까우면 다른 레인으로 보내거나 밀어낸다. */
const LABEL_GAP = 10;
type Point = { name: string; value: number; tone: Tone; strong?: boolean; place?: 'above' | 'below' };
export type SpectrumBid = { name: string; value: number; isWinner?: boolean };
type Mark = { key: string; name: string; value: number; dot: string; tone?: string; strong?: boolean };
type Placed = { left: number; lane: 0 | 1 };
/**
* 단가 조정 흐름 스펙트럼 — 얇은 바에 목표가·최저·최고 투찰가를 찍고 값 라벨을 바로 옆에 붙인다.
* 값은 buildQuotationResult 파생값(별도 컬럼 없음). 위치는 세 값 min~max 도메인 선형 배치라 목표가가 범위 밖이어도 안 깨진다.
* 라벨 방향(위/아래)은 값 순 정렬 후 번갈아 배치 → 위치가 가까운(정렬상 인접) 라벨끼리 항상 반대쪽이라 안 겹친다.
* 가격 스펙트럼 — 목표가·타결 상한가를 세로 게이트로 세우고 그 사이를 타결 구간으로 칠한다.
* 상한 초과 구역은 결렬 색. 협력사 제출가는 점으로 찍고 낙찰(또는 최저가)만 강조한다.
*
* 라벨은 자기 기준선 위치에 붙인다. 겹침은 렌더 후 폭을 실측해 위/아래 두 레인으로 나누고,
* 같은 레인에서 부딪히면 오른쪽으로 밀어 해결한다(양 끝은 트랙 안으로 clamp).
*/
export function PricingSpectrum({
targetPrice,
lowestBid,
highestBid,
ceilingPrice,
anchorPrice,
bids,
}: {
targetPrice: number | null;
lowestBid: number | null;
highestBid: number | null;
/** 타결 상한가 — 이 위는 결렬 구간. */
ceilingPrice: number | null;
/** 1:1 협상에서만. 1:N 은 협력사마다 달라 대표값이 없다. */
anchorPrice?: number | null;
/** 가격을 제출한 협력사들(투찰가 또는 거부 시 희망가). */
bids: SpectrumBid[];
}) {
// 투찰 0건 → 목표가만 한 줄(폴백). lowestBid/highestBid 는 같은 배열에서 나와 함께 null.
if (lowestBid == null || highestBid == null) {
const winner = bids.find((b) => b.isWinner) ?? null;
const lowest = bids.length ? bids.reduce((a, b) => (b.value < a.value ? b : a)) : null;
const spot = winner ?? lowest; // 강조점 — 낙찰가가 있으면 그것, 없으면 최저 제출가.
// 라벨을 다는 기준값들(값 오름차순). 나머지 제출가는 점만 찍고 title 로 알려준다.
const marks: Mark[] = [
anchorPrice != null ? { key: 'anchor', name: '앵커링가', value: anchorPrice, dot: 'bg-zinc-400' } : null,
targetPrice != null ? { key: 'target', name: '목표가', value: targetPrice, dot: 'bg-primary', tone: 'text-primary' } : null,
ceilingPrice != null
? { key: 'ceiling', name: '타결 상한', value: ceilingPrice, dot: 'bg-amber-500', tone: 'text-amber-600 dark:text-amber-400' }
: null,
spot
? {
key: 'spot',
name: winner ? `낙찰 · ${winner.name}` : `최저 · ${spot.name}`,
value: spot.value,
dot: winner ? 'bg-emerald-500' : 'bg-zinc-500',
tone: winner ? 'text-emerald-600 dark:text-emerald-400' : undefined,
strong: true,
}
: null,
]
.filter((m): m is Mark => m != null)
.sort((a, b) => a.value - b.value);
const values = [...marks.map((m) => m.value), ...bids.map((b) => b.value)];
const trackRef = useRef<HTMLDivElement>(null);
const labelRefs = useRef<(HTMLSpanElement | null)[]>([]);
const [placed, setPlaced] = useState<Placed[]>([]);
// 축 도메인. 타결 상한가가 최댓값이면(= 상한을 넘긴 제출이 없으면) 위쪽에 여유를 크게 둬서
// '초과 구간'이 눈에 보이게 한다 — 여유가 없으면 상한선이 트랙 끝에 처박혀 결렬 구간이 사라진다.
const lo = values.length ? Math.min(...values) : 0;
const hi = values.length ? Math.max(...values) : 0;
const base = hi - lo || Math.max(hi * 0.02, 1);
const padHi = ceilingPrice != null && hi <= ceilingPrice ? base * 0.22 : base * 0.08;
const min = lo - base * 0.08;
const span = hi + padHi - min;
const posOf = (v: number) => clamp(span > 0 ? ((v - min) / span) * 100 : 50, 0, 100);
// 렌더된 라벨 폭을 재서 레인·위치를 정한다. 폭이 바뀌면(창 크기·글꼴) 다시 잰다.
useLayoutEffect(() => {
const track = trackRef.current;
if (!track) return;
const layout = () => {
const trackW = track.clientWidth;
if (!trackW) return;
const laneEnd: [number, number] = [-Infinity, -Infinity];
const next: Placed[] = marks.map((m, i) => {
const w = labelRefs.current[i]?.offsetWidth ?? 0;
const wanted = clamp((posOf(m.value) / 100) * trackW - w / 2, 0, Math.max(trackW - w, 0));
// 부딪히지 않는 레인을 먼저 찾고, 둘 다 막히면 덜 채워진 레인에서 오른쪽으로 민다.
const fits0 = wanted >= laneEnd[0] + LABEL_GAP;
const fits1 = wanted >= laneEnd[1] + LABEL_GAP;
const lane: 0 | 1 = fits0 ? 0 : fits1 ? 1 : laneEnd[0] <= laneEnd[1] ? 0 : 1;
const left = clamp(Math.max(wanted, laneEnd[lane] + LABEL_GAP), 0, Math.max(trackW - w, 0));
laneEnd[lane] = left + w;
return { left, lane };
});
setPlaced(next);
};
layout();
const ro = new ResizeObserver(layout);
ro.observe(track);
return () => ro.disconnect();
// 값 목록이 바뀌면 다시 배치한다(라벨 문자열·개수가 바뀌므로).
}, [marks.map((m) => `${m.key}:${m.value}:${m.name}`).join('|')]); // eslint-disable-line react-hooks/exhaustive-deps
if (values.length === 0) {
return (
<Typography as="p" variant="caption" className="text-[11px]">
<span className="text-amber-600">목표가</span>{' '}
<span className="font-mono font-semibold text-foreground">{won(targetPrice)}</span>
<span className="text-muted-foreground"> · 투찰 없음</span>
표시할 가격이 없습니다.
</Typography>
);
}
const singleBid = lowestBid === highestBid; // 투찰 1건 → 최저=최고, 라벨 하나로 축약.
// 표시할 점(목표가는 없을 수 있음). 값 순으로 정렬해 라벨 방향을 번갈아(below/above) 주면
// 위치가 가까운(정렬상 인접) 라벨끼리 항상 반대쪽에 놓여 안 겹친다.
const points: Point[] = [
targetPrice != null ? { name: '목표가', value: targetPrice, tone: 'amber' } : null,
{ name: singleBid ? '투찰가' : '최저 투찰가', value: lowestBid, tone: 'emerald', strong: true },
singleBid ? null : { name: '최고 투찰가', value: highestBid, tone: 'zinc' },
].filter((p): p is Point => p != null);
const vals = points.map((p) => p.value);
const min = Math.min(...vals);
const max = Math.max(...vals);
const span = max - min;
const posOf = (v: number) => (span > 0 ? ((v - min) / span) * 100 : 50);
[...points]
.sort((a, b) => a.value - b.value)
.forEach((p, i) => {
p.place = i % 2 === 0 ? 'below' : 'above';
});
// 아무도 가격을 내지 않았으면 타결/결렬 구간을 색으로 단정하지 않는다 — 판정할 대상이 없다.
const hasBids = bids.length > 0;
const laneUsed = (lane: 0 | 1) => placed.some((p) => p.lane === lane);
return (
<div className="w-full px-1">
<div className="relative mx-1 my-3.5 h-1">
{/* 트랙 */}
<div className="absolute inset-x-0 top-1/2 h-1 -translate-y-1/2 rounded-full bg-border/60" />
{/* 투찰 스프레드(최저~최고) */}
{!singleBid && (
<div
className="absolute top-1/2 h-1 -translate-y-1/2 rounded-full bg-gradient-to-r from-emerald-400 to-zinc-300"
style={{ left: `${posOf(lowestBid)}%`, width: `${posOf(highestBid) - posOf(lowestBid)}%` }}
/>
)}
{points.map((p) => (
<Fragment key={p.name}>
<Dot pos={posOf(p.value)} tone={p.tone} strong={p.strong} />
<BarLabel
pos={posOf(p.value)}
place={p.place ?? 'below'}
name={p.name}
value={won(p.value)}
tone={p.tone}
strong={p.strong}
<div className="w-full">
{/* 위 레인 자리(라벨이 올라갈 때만 높이 확보) */}
<div className={cn('relative', laneUsed(1) ? 'h-6' : 'h-0')} aria-hidden />
<div ref={trackRef} className="relative h-1.5">
<div className="absolute inset-x-0 top-1/2 h-1.5 -translate-y-1/2 rounded-full bg-muted" />
{/* 타결 구간(상한 이하) / 상한 초과 구간 */}
{ceilingPrice != null && (
<>
<div
className={cn(
'absolute top-1/2 h-1.5 -translate-y-1/2 rounded-l-full',
hasBids ? 'bg-emerald-100 dark:bg-emerald-950/60' : 'bg-muted-foreground/15',
)}
style={{ left: 0, width: `${posOf(ceilingPrice)}%` }}
/>
</Fragment>
<div
className={cn(
'absolute top-1/2 h-1.5 -translate-y-1/2 rounded-r-full',
hasBids ? 'bg-rose-100 dark:bg-rose-950/50' : 'bg-muted-foreground/25',
)}
style={{ left: `${posOf(ceilingPrice)}%`, right: 0 }}
/>
</>
)}
{/* 판정 게이트 */}
{anchorPrice != null && <Gate pos={posOf(anchorPrice)} className="bg-zinc-400" />}
{targetPrice != null && <Gate pos={posOf(targetPrice)} className="bg-primary" />}
{ceilingPrice != null && <Gate pos={posOf(ceilingPrice)} className="bg-amber-500" />}
{/* 협력사 제출가 */}
{bids.map((b) => (
<span
key={`${b.name}-${b.value}`}
title={`${b.name} · ${won(b.value)}`}
className={cn(
'absolute top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-card',
b.isWinner
? 'size-3.5 bg-emerald-500 ring-2 ring-emerald-200 dark:ring-emerald-900'
: 'size-2.5 bg-zinc-400 dark:bg-zinc-500',
)}
style={{ left: `${posOf(b.value)}%` }}
/>
))}
{/* 라벨 — 실측 배치. 첫 렌더(placed 비어있음)에는 기준선 위치에 그대로 두고 바로 재배치된다. */}
{marks.map((m, i) => {
const p = placed[i];
const lane = p?.lane ?? 0;
return (
<span
key={m.key}
ref={(el) => {
labelRefs.current[i] = el;
}}
className={cn(
'absolute inline-flex items-center gap-1 whitespace-nowrap leading-none',
lane === 0 ? 'top-3.5' : 'bottom-3.5',
)}
style={
p
? { left: `${p.left}px` }
: { left: `${posOf(m.value)}%`, transform: 'translateX(-50%)', visibility: 'hidden' }
}
>
<span className={cn('size-1.5 shrink-0 rounded-full', m.dot)} />
<Typography as="span" variant="caption" className={cn('text-[10px]', m.tone)}>
{m.name}
</Typography>
<Typography
as="span"
variant="small"
className={cn(
'font-mono text-[10.5px] tabular-nums text-foreground',
m.strong ? 'font-bold' : 'font-semibold',
m.tone,
)}
>
{won(m.value)}
</Typography>
</span>
);
})}
</div>
{/* 아래 레인 자리. 제출 건수는 있을 때만 — 없다는 사실은 상단 결과 배지와 레일이 이미 말한다. */}
<div className={cn(laneUsed(0) ? 'mt-6' : 'mt-1.5')}>
{hasBids && (
<Typography as="span" variant="caption" className="text-[10.5px]">
제출 {bids.length}건
</Typography>
)}
</div>
</div>
);
}
/** 트랙 위 점. 위치는 0~100% 로 클램프. */
function Dot({ pos, tone, strong }: { pos: number; tone: Tone; strong?: boolean }) {
/** 트랙을 가로지르는 판정선. */
function Gate({ pos, className }: { pos: number; className: string }) {
return (
<div
className={cn(
'absolute top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2 ring-background',
strong ? 'h-2.5 w-2.5' : 'h-2 w-2',
TONE_DOT[tone],
)}
style={{ left: `${clamp(pos, 0, 100)}%` }}
<span
className={cn('absolute -top-1.5 -bottom-1.5 w-0.5 -translate-x-1/2 rounded-full', className)}
style={{ left: `${pos}%` }}
/>
);
}
/** 점 위/아래 한 줄 라벨(이름+금액). 양 끝에선 안쪽으로 정렬해 넘침 방지. */
function BarLabel({
pos,
place,
name,
value,
tone,
strong,
}: {
pos: number;
place: 'above' | 'below';
name: string;
value: string;
tone: Tone;
strong?: boolean;
}) {
const align =
pos <= 8 ? 'translate-x-0 text-left' : pos >= 92 ? '-translate-x-full text-right' : '-translate-x-1/2 text-center';
return (
<div
className={cn(
'absolute whitespace-nowrap leading-none',
place === 'above' ? 'bottom-full mb-1' : 'top-full mt-1',
align,
)}
style={{ left: `${clamp(pos, 0, 100)}%` }}
>
<Typography as="span" variant="caption" className={cn('text-[10px]', TONE_TEXT[tone])}>
{name}{' '}
</Typography>
<Typography
as="span"
variant="small"
className={cn('font-mono text-[11px] text-foreground', strong ? 'font-bold' : 'font-semibold')}
>
{value}
</Typography>
</div>
);
}
@@ -183,7 +183,7 @@ export function RegenerateModal({
<div className="my-4 space-y-4 text-xs">
{/* ── 직전 라운드 결과 — 무엇을 바꿔야 할지의 근거 ── */}
<Section title="직전 라운드 결과" sub={`${quotation.round ?? 1}차`}>
<ResultSummaryBand quotation={quotation} sessionViews={sessionViews} />
<ResultSummaryBand quotation={quotation} sessionViews={sessionViews} ceilingRate={inheritedCeilingRate} />
{hint && (
<div className="mt-2 flex items-start gap-2 rounded border border-amber-200 bg-amber-50/60 dark:border-amber-900/50 dark:bg-amber-950/20 px-2.5 py-2">
<Lightbulb size={13} className="mt-0.5 shrink-0 text-amber-600" />
@@ -1,20 +1,20 @@
import type { ReactNode } from 'react';
import { BadgeCheck, TrendingDown, TrendingUp } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { BadgeCheck } from 'lucide-react';
import { Typography } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
import type { QuotationData } from '@/api/generated/model/quotationData';
import { StatusPill, type PillTone } from './StatusPill';
import { PricingSpectrum } from './PricingSpectrum';
import { StatusPill, sessionStatusTone, type PillTone } from './StatusPill';
import { PricingSpectrum, type SpectrumBid } from './PricingSpectrum';
import { SessionStatus } from '@/api/generated/model';
import {
awardPrice,
buildQuotationResult,
ceilingPriceOf,
is1v1,
sessionStatusLabel,
CHAIN_ROUND_STATE_LABEL,
type ChainRoundState,
type SessionView,
} from '../../types';
const won = (n?: number | null) => (n != null ? `₩${n.toLocaleString()}` : '-');
// 결과 상태별 배지 톤(협상현황 pill 팔레트 재사용). 개찰=주황(낙찰자 미정, 수동 처리 필요).
const OUTCOME_TONE: Record<ChainRoundState, PillTone> = {
awarded: 'emerald',
@@ -22,85 +22,86 @@ const OUTCOME_TONE: Record<ChainRoundState, PillTone> = {
active: 'zinc',
};
/** 견적 결과 요약 밴드 — 마감 사유/낙찰 협력사 + 절감, 하단에 단가 조정 흐름 스펙트럼(최고·최저 투찰가/목표가). */
/**
* 결과 요약 밴드 — 마감 결과/사유와 낙찰 협력사, 그리고 가격 스펙트럼.
* 금액(목표가·상한가·낙찰가·절감)은 헤더 가격 레일이 책임진다. 여기서 되풀이하지 않는다.
*/
export function ResultSummaryBand({
quotation,
sessionViews,
ceilingRate,
}: {
quotation: QuotationData;
sessionViews: SessionView[];
/** 타결 상한율(‰) — 견적 override 없으면 적용 세팅값. */
ceilingRate: number;
}) {
const r = buildQuotationResult(quotation, sessionViews);
const good = r.savings != null && r.savings >= 0;
const pct = r.savingsRate != null ? `${Math.abs(r.savingsRate * 100).toFixed(1)}%` : null;
const SavingsIcon = good ? TrendingDown : TrendingUp;
const rep = sessionViews.find((s) => s.target_price > 0) ?? sessionViews[0];
const winnerId = quotation.preferred_sp_id ?? null;
// 1:1 은 협력사가 하나라 그 세션이 곧 이 협상이다(세션이 여럿이면 대표를 세우지 않는다).
const oneToOne = is1v1(quotation.type);
const solo = oneToOne && sessionViews.length === 1 ? sessionViews[0] : null;
// 가격을 제출한 협력사만 점으로. 낙찰자는 강조.
const bids: SpectrumBid[] = sessionViews.flatMap((s) => {
const value = awardPrice(s);
if (value == null) return [];
return [{ name: s.supplier_name, value, isWinner: winnerId != null && s.supplier_id === winnerId }];
});
return (
<Card className="p-2.5 gap-2 rounded shadow-xs border-border/80 flex flex-col">
{/* 결과/사유 + 낙찰 협력사 + 절감 */}
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<StatusPill tone={OUTCOME_TONE[r.outcome]}>{CHAIN_ROUND_STATE_LABEL[r.outcome]}</StatusPill>
{/* 낙찰 건은 협력사명을 주줄로(사유 '낙찰'은 pill 과 중복이라 생략), 그 외엔 마감사유를 표기. */}
{r.winnerName ? (
<div className="min-w-0">
<Typography as="p" variant="caption" className="text-[10px] leading-tight text-muted-foreground">
낙찰 협력사
</Typography>
<Typography
as="p"
variant="small"
className="flex items-center gap-1 text-[12px] font-bold font-sans text-foreground truncate"
>
<BadgeCheck size={13} className="text-emerald-600 shrink-0" />
{r.winnerName}
</Typography>
</div>
) : (
<Typography as="p" variant="small" className="text-[12px] font-bold truncate min-w-0">
{r.closeReason}
<div className="flex flex-col gap-3 rounded border border-border/80 bg-card p-3 shadow-xs">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
{/* 1:1 은 협력사가 하나라 세션 상태가 곧 이 협상의 결과다 — 견적 결과 배지까지 붙이면
'거부해서 개찰됐다'는 한 사실을 배지 두 개로 두 번 말하게 된다(견적 결과는 가격 레일이 말한다). */}
{solo ? (
<>
<Typography as="span" variant="small" className="truncate font-sans text-[12px] font-bold text-foreground">
{solo.supplier_name}
</Typography>
)}
</div>
<Stat label={r.provisional ? '예상 절감' : '목표가 대비'}>
{r.savings == null ? (
<Typography as="span" variant="small" className="font-mono text-muted-foreground text-[13px]">
-
</Typography>
) : (
<Typography
as="span"
variant="small"
className={cn(
'inline-flex items-center gap-1 font-mono font-bold text-[13px]',
good ? 'text-emerald-600' : 'text-amber-600',
)}
{/* 마감된 1:1 은 '무엇을 했고(세션) 그래서 어떻게 끝났는지(견적)'가 한 사실이라 배지 하나로 잇는다.
진행 중이면 견적 결과가 '진행중'이라 같은 말이 되므로 세션 상태만. */}
<StatusPill
tone={
solo.status === SessionStatus.REJECTED
? 'rose' // 거부는 결과(개찰)보다 강한 신호다 — 색을 결과 톤에 묻히게 두지 않는다.
: r.outcome === 'active'
? sessionStatusTone(solo.status)
: OUTCOME_TONE[r.outcome]
}
>
<SavingsIcon size={13} />
{good ? '' : '−'}
{won(Math.abs(r.savings))}
{pct ? ` (${pct})` : ''}
</Typography>
)}
</Stat>
{r.outcome === 'active'
? sessionStatusLabel(solo.status)
: `${sessionStatusLabel(solo.status)} — ${CHAIN_ROUND_STATE_LABEL[r.outcome]}`}
</StatusPill>
</>
) : (
<StatusPill tone={OUTCOME_TONE[r.outcome]}>{CHAIN_ROUND_STATE_LABEL[r.outcome]}</StatusPill>
)}
{solo ? null : r.winnerName ? (
<Typography
as="p"
variant="small"
className="flex min-w-0 items-center gap-1 truncate font-sans text-[12px] font-bold text-foreground"
>
<BadgeCheck size={13} className="shrink-0 text-emerald-600" />
{r.winnerName}
</Typography>
) : (
<Typography as="p" variant="small" className="min-w-0 truncate text-[12px] font-bold">
{r.closeReason}
</Typography>
)}
</div>
{/* 단가 조정 흐름 스펙트럼: 최고 투찰가 → 최저 투찰가 · 목표가 */}
<PricingSpectrum targetPrice={r.targetPrice} lowestBid={r.lowestBid} highestBid={r.highestBid} />
</Card>
);
}
/** 밴드 안의 라벨/값 한 칸. */
function Stat({ label, sub, children }: { label: string; sub?: string; children: ReactNode }) {
return (
<div className="flex flex-col justify-center rounded border border-border bg-muted/30 px-3 py-1.5 min-w-[108px]">
<Typography as="span" variant="caption" className="text-[10px] leading-tight">
{label}
{sub ? ` · ${sub}` : ''}
</Typography>
{children}
<PricingSpectrum
targetPrice={r.targetPrice}
ceilingPrice={ceilingPriceOf(rep, ceilingRate)}
anchorPrice={is1v1(quotation.type) ? (rep?.anchoring_price ?? null) : null}
bids={bids}
/>
</div>
);
}
@@ -9,7 +9,8 @@ import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@
import { SessionStatus } from '@/api/generated/model';
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip';
import { StatusPill, sessionStatusTone } from './StatusPill';
import { awardPrice, mapServerSessionView, sessionStatusLabel } from '../../types';
import { AwardModal } from './AwardModal';
import { awardPrice, offlineAward, mapServerSessionView, sessionStatusLabel } from '../../types';
import { useCompanySettings } from '@/features/settings/useCompanySettings';
type SessionView = ReturnType<typeof mapServerSessionView>;
@@ -37,7 +38,7 @@ export function SessionsStatusTab({
/** 한 세션(공급사)에 초청 메일 발송/재발송. */
onNotifyOne: (sessionId: string) => Promise<void>;
/** 고른 협력사를 낙찰 처리. 성공 시 true. */
onAward: (supplierId: string, supplierName: string) => Promise<boolean>;
onAward: (supplierId: string, supplierName: string, contractPrice: number, contractNote: string) => Promise<boolean>;
}) {
const { settings } = useCompanySettings();
const sessionFields = settings.session_fields ?? [];
@@ -55,34 +56,32 @@ export function SessionsStatusTab({
const [sendingId, setSendingId] = useState<string | null>(null);
const [selectedWinnerId, setSelectedWinnerId] = useState<string | null>(null);
const [awarding, setAwarding] = useState(false);
const [awardOpen, setAwardOpen] = useState(false);
const unsentCount = sessionViews.filter((s) => !s.email_sent_at).length;
// 낙찰 후보 = 가격을 써낸 협력사(투찰한 협상완료 + 공급 희망가를 남긴 협상거부).
// 협상이 결렬돼도 최종 제출가로 계약을 진행하므로 거부 건도 후보에 넣는다.
const candidates = sessionViews.filter((s) => awardPrice(s) != null);
// 낙찰 후보 = 이 견적에 초청된 협력사 전부. 결렬·미응찰 건은 오프라인으로 다시 협상하고 그 결과를
// 반영하는 자리라, 시스템에 가격을 안 낸 협력사도 고를 수 있어야 한다(계약가는 담당자가 입력).
const candidates = sessionViews;
const showAward = canAward && candidates.length > 0;
// 최저가 = 자동낙찰과 같은 기준 → 추천 표시(담당자가 동가/사정상 다른 곳을 골라도 됨).
const lowestBid = candidates.length ? Math.min(...candidates.map((s) => awardPrice(s) as number)) : null;
// 최저 제출가 = 자동낙찰과 같은 기준 → 추천 표시(담당자가 동가/사정상 다른 곳을 골라도 됨).
const submitted = candidates.map(awardPrice).filter((v): v is number => v != null);
const lowestBid = submitted.length ? Math.min(...submitted) : null;
const selectedWinner = candidates.find((s) => s.supplier_id === selectedWinnerId) ?? null;
const colCount = showAward ? 13 : 12;
// 상품은 견적당 하나다 — 모든 행이 같은 값이라 컬럼을 두지 않는다(헤더 상품 카드가 정본).
// 마감시각은 세션 컬럼이라 갈릴 수 있어, 실제로 다를 때만 세운다.
const showEndTimeCol = new Set(sessionViews.map((s) => s.end_time)).size > 1;
const colCount = (showAward ? 13 : 12) - (showEndTimeCol ? 0 : 1);
const handleAward = async () => {
if (!selectedWinner) return;
const name = selectedWinner.supplier_name;
const winnerPrice = awardPrice(selectedWinner);
const price = winnerPrice != null ? `₩${winnerPrice.toLocaleString()}` : '-';
if (
!(await confirm({
title: '직접 낙찰',
description: `[${name}] (계약가 ${price})을(를) 낙찰 처리하시겠습니까? 낙찰은 되돌릴 수 없습니다.`,
confirmText: '낙찰 확정',
}))
)
return;
const handleAward = async (contractPrice: number, contractNote: string): Promise<boolean> => {
if (!selectedWinner) return false;
setAwarding(true);
try {
const ok = await onAward(selectedWinner.supplier_id, name);
if (ok) setSelectedWinnerId(null);
const ok = await onAward(selectedWinner.supplier_id, selectedWinner.supplier_name, contractPrice, contractNote);
if (ok) {
setSelectedWinnerId(null);
setAwardOpen(false);
}
return ok;
} finally {
setAwarding(false);
}
@@ -156,7 +155,7 @@ export function SessionsStatusTab({
{selectedWinner && <span className="ml-1 font-bold">선택: {selectedWinner.supplier_name}</span>}
</Typography>
<button
onClick={handleAward}
onClick={() => setAwardOpen(true)}
disabled={!selectedWinner || awarding}
title={selectedWinner ? '선택한 협력사를 낙찰 처리합니다.' : '먼저 낙찰할 협력사를 선택하세요.'}
className="flex shrink-0 items-center gap-2 px-3 py-2 bg-success text-white text-xs font-bold rounded hover:bg-success/90 cursor-pointer transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
@@ -168,22 +167,22 @@ export function SessionsStatusTab({
)}
<div className="hidden xl:block border border-border rounded-lg bg-card overflow-x-auto">
<Table className="w-full text-left text-xs border-collapse font-mono min-w-[1250px]">
<Table className={cn('w-full text-left text-xs border-collapse font-mono', showEndTimeCol ? 'min-w-[1140px]' : 'min-w-[1040px]')}>
<TableHeader className="bg-muted text-muted-foreground text-[10px] border-b border-border">
<TableRow>
{showAward && <TableHead className="p-3 font-semibold text-center font-sans w-14">낙찰선택</TableHead>}
<TableHead className="p-3 font-semibold font-sans">협력사</TableHead>
<TableHead className="p-2 font-semibold text-center w-10">URL</TableHead>
<TableHead className="p-3 font-semibold text-center font-sans">초청메일</TableHead>
<TableHead className="p-3 font-semibold font-sans">상품</TableHead>
<TableHead className="p-3 font-semibold text-center font-sans">협상상태</TableHead>
<TableHead className="p-3 font-semibold text-right">앵커링가</TableHead>
<TableHead className="p-3 font-semibold text-right">투찰가</TableHead>
<TableHead className="p-3 font-semibold">투찰시각</TableHead>
<TableHead className="p-3 font-semibold">마감시각</TableHead>
{showEndTimeCol && <TableHead className="p-3 font-semibold">마감시각</TableHead>}
<TableHead className="p-3 font-semibold font-sans">거부사유</TableHead>
<TableHead className="p-3 font-semibold text-right">거부가격</TableHead>
<TableHead className="p-3 font-semibold font-sans">거부배송방식</TableHead>
<TableHead className="p-3 font-semibold font-sans">부가정보</TableHead>
</TableRow>
</TableHeader>
<TableBody className="divide-y divide-border">
@@ -195,7 +194,7 @@ export function SessionsStatusTab({
</TableRow>
)}
{sessionViews.map((sess) => {
const isCandidate = awardPrice(sess) != null;
const isCandidate = true; // 오프라인 협상 반영 — 가격을 안 낸 협력사도 낙찰 대상
const isRecommended = isCandidate && awardPrice(sess) === lowestBid;
const isWinner = !!winnerSupplierId && sess.supplier_id === winnerSupplierId;
return (
@@ -314,7 +313,6 @@ export function SessionsStatusTab({
)}
</div>
</TableCell>
<TableCell className="p-3 font-semibold font-sans">{sess.item_name}</TableCell>
<TableCell className="p-3 text-center">
<StatusPill tone={sessionStatusTone(sess.status)}>{sessionStatusLabel(sess.status)}</StatusPill>
</TableCell>
@@ -334,14 +332,24 @@ export function SessionsStatusTab({
</TableCell>
<TableCell className="p-3 text-right font-bold text-foreground">
{sess.bid_price ? `₩${sess.bid_price.toLocaleString()}` : '-'}
{offlineAward(sess) && (
<Typography as="span" variant="caption" className="block text-[10px] font-bold text-success">
계약 ₩{offlineAward(sess)!.price.toLocaleString()}
</Typography>
)}
</TableCell>
<TableCell className="p-3 text-muted-foreground">{sess.bid_at || '-'}</TableCell>
<TableCell className="p-3 text-muted-foreground font-sans">{sess.end_time || '-'}</TableCell>
{showEndTimeCol && (
<TableCell className="p-3 text-muted-foreground font-sans">{sess.end_time || '-'}</TableCell>
)}
<TableCell className="p-3 text-rose-600 font-sans">{sess.reject_reason || '-'}</TableCell>
<TableCell className="p-3 text-right text-rose-600 font-mono">
{sess.reject_price ? `₩${sess.reject_price.toLocaleString()}` : '-'}
</TableCell>
<TableCell className="p-3 text-muted-foreground font-sans">{sess.reject_delivery_type || '-'}</TableCell>
<TableCell className="p-3 font-sans">
<ExtraInfoCell rows={extraRows(sess)} onOpen={() => setExtraSession(sess)} />
</TableCell>
</TableRow>
);
})}
@@ -357,23 +365,28 @@ export function SessionsStatusTab({
</Typography>
)}
{sessionViews.map((sess) => {
const isCandidate = awardPrice(sess) != null;
const isCandidate = true; // 오프라인 협상 반영 — 가격을 안 낸 협력사도 낙찰 대상
const isRecommended = isCandidate && awardPrice(sess) === lowestBid;
const isWinner = !!winnerSupplierId && sess.supplier_id === winnerSupplierId;
const rows: { label: string; value: string }[] = [
{ label: '상품', value: sess.item_name || '-' },
{
label: '앵커링가',
value: sess.anchoring_price > 0 ? `₩${sess.anchoring_price.toLocaleString()}` : '-',
},
{ label: '투찰가', value: sess.bid_price ? `₩${sess.bid_price.toLocaleString()}` : '-' },
{ label: '투찰시각', value: sess.bid_at || '-' },
{ label: '마감시각', value: sess.end_time || '-' },
];
// 거부 정보는 값이 있을 때만(빈 줄로 카드가 길어지지 않게).
if (sess.reject_reason) rows.push({ label: '거부사유', value: sess.reject_reason });
if (sess.reject_price) rows.push({ label: '거부가격', value: `₩${sess.reject_price.toLocaleString()}` });
if (sess.reject_delivery_type) rows.push({ label: '거부배송방식', value: sess.reject_delivery_type });
const offline = offlineAward(sess);
if (offline) rows.push({ label: '계약가(오프라인)', value: `₩${offline.price.toLocaleString()}` });
if (showEndTimeCol) rows.push({ label: '마감시각', value: sess.end_time || '-' });
const extras = extraRows(sess);
if (extras.length > 0) {
rows.push({ label: '부가정보', value: extras.map((r) => `${r.label} ${String(r.value)}`).join(' · ') });
}
return (
<div key={sess.session_id} className={cn('p-3', isWinner && 'bg-success/10')}>
<div className="flex items-center gap-2">
@@ -489,6 +502,37 @@ export function SessionsStatusTab({
</div>
</div>
)}
{awardOpen && selectedWinner && (
<AwardModal
open={awardOpen}
winner={selectedWinner}
onConfirm={handleAward}
onClose={() => setAwardOpen(false)}
/>
)}
</div>
);
}
/** 협상현황 표의 부가정보 칸 — 입력값을 한 줄로 요약하고, 클릭하면 전체를 모달로 연다. */
function ExtraInfoCell({
rows,
onOpen,
}: {
rows: { label: string; value: unknown }[];
onOpen: () => void;
}) {
if (rows.length === 0) return <span className="text-muted-foreground">-</span>;
const text = rows.map((r) => `${r.label} ${String(r.value)}`).join(' · ');
return (
<button
type="button"
onClick={onOpen}
title={text}
className="block max-w-[220px] truncate text-left text-emerald-700 hover:underline cursor-pointer dark:text-emerald-400"
>
{text}
</button>
);
}
@@ -22,12 +22,16 @@ import {
mapSetting,
mapServerSessionView,
mapServerCardView,
buildPriceRail,
quotationTypeLabel,
chainRoundState,
type NegotiationCard,
} from '../../types';
import { QuotationStatus } from '@/api/generated/model';
import { DrawerHeaderCards } from './DrawerHeaderCards';
import { PriceRail } from './PriceRail';
import { RoundTimeline } from './RoundTimeline';
import { StatusPill } from './StatusPill';
import { RegenerateModal } from './RegenerateModal';
import type { RegenerateInput } from '../../hooks/useQuotations';
import { SessionsStatusTab } from './SessionsStatusTab';
@@ -41,7 +45,13 @@ type QuotationDetailSheetProps = {
quotation: QuotationData;
onCloseQuotation: (id: string, name: string) => void;
/** 개찰(낙찰자 미정 마감) 견적을 협상현황 표에서 직접 낙찰. 성공 시 true. */
onAward: (qtId: string, winnerSupplierId: string, winnerName: string) => Promise<boolean>;
onAward: (
qtId: string,
winnerSupplierId: string,
winnerName: string,
contractPrice: number,
contractNote: string,
) => Promise<boolean>;
/** 라운드 타임라인에서 다른 차수로 전환(같은 견적번호의 다른 견적 상세 열기). */
onSwitchRound: (qtId: string) => void;
/** 마감된 견적의 다음 라운드를 수동 생성(공급사·기한·목표가·카드 재선택). 성공 시 새 qt_id 반환. */
@@ -139,6 +149,11 @@ export function QuotationDetailSheet({
// 세션은 모두 같은 상품을 가리키므로(1견적=1상품) 단건 상품 하나로 item_name 해석이 끝난다.
const productList = currentProduct ? [currentProduct] : [];
const sessionViews = serverSessions.map((sd) => mapServerSessionView(sd, partners, productList));
// 헤더에 고정할 가격 레일 — 접힘/펼침·탭과 무관하게 항상 같은 값을 본다.
const railCeilingRate = quotation.done_ceiling_rate ?? settingCeilingRate;
const priceRail = buildPriceRail(quotation, sessionViews, railCeilingRate);
const railTargetSessionId =
(sessionViews.find((s) => s.target_price > 0) ?? sessionViews[0])?.session_id ?? null;
const quotationCardViews = serverCards.map(mapServerCardView);
// 헤더 상단바·마감 버튼에 필요한 최소 표시값만 (나머지 견적 표시값은 DrawerHeaderCards 내부 계산).
@@ -182,10 +197,13 @@ export function QuotationDetailSheet({
<div className="shrink-0 px-6 pt-6 pb-3 bg-muted/30">
<div className="flex items-start justify-between">
<div>
<div className="flex items-center gap-2 text-muted-foreground text-[10px] font-mono tracking-widest uppercase">
<span>견적 상세 // {q_number}</span>
<Typography variant="h3">{q_name}</Typography>
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
<span className="font-mono text-[12px] font-bold tracking-tight text-foreground">{q_number}</span>
<StatusPill tone="zinc">{quotationTypeLabel(quotation.type)}</StatusPill>
{/* 차수는 라운드가 하나뿐이라 타임라인이 안 뜰 때만 — 뜨면 그쪽이 현재 차수를 보여준다. */}
{chainRounds.length <= 1 && <StatusPill tone="zinc">{quotation.round ?? 1}차</StatusPill>}
</div>
<Typography variant="h3" className="mt-1">{q_name}</Typography>
{quotation.number && (
<RoundTimeline number={quotation.number} currentQtId={qtId} onSwitchRound={onSwitchRound} />
)}
@@ -252,11 +270,19 @@ export function QuotationDetailSheet({
</div>
</div>
{/* 가격 레일 — 접힘·펼침·탭 전환과 무관하게 항상 붙어 있다. 상세를 펼쳐 스크롤해도 기준가는 남는다. */}
<div className="shrink-0">
<PriceRail
rail={priceRail}
onShowTarget={railTargetSessionId ? () => setTargetSessionId(railTargetSessionId) : undefined}
/>
</div>
{/* 견적 상세 정보 — 펼치면 탭과 flex 비율(헤더:탭 = 2:1)로 높이를 나눠 가지고 자체 스크롤 */}
{showHeaderCards ? (
{showHeaderCards && (
<div
style={{ flex: '2 1 0%' }}
className="min-h-0 overflow-y-auto overscroll-contain px-6 pb-6 bg-muted/30 border-b border-border"
className="min-h-0 overflow-y-auto overscroll-contain px-6 py-4 bg-muted/30 border-b border-border"
>
<DrawerHeaderCards
quotation={quotation}
@@ -266,18 +292,6 @@ export function QuotationDetailSheet({
onShowTarget={setTargetSessionId}
/>
</div>
) : (
/* 접어도 결과 요약(목표가·낙찰·절감) 밴드는 상단에 그대로 남긴다. */
<div className="shrink-0 px-6 pt-4 pb-4 bg-muted/30 border-b border-border">
<DrawerHeaderCards
collapsed
quotation={quotation}
quotationSettings={quotationSettings}
sessionViews={sessionViews}
currentProduct={currentProduct}
onShowTarget={setTargetSessionId}
/>
</div>
)}
{/* Tabs */}
@@ -290,12 +304,10 @@ export function QuotationDetailSheet({
key={tab.id}
onClick={() => {
setActiveTab(tab.id);
if (tab.id === 'chat') {
// 협상 대화 탭에선 대화 영역을 넓게 쓰도록 견적 상세 정보를 접는다.
setShowHeaderCards(false);
if (serverSessions.length > 0 && !selectedSessionId) {
setSelectedSessionId(serverSessions[0].session_id);
}
// 탭을 고르면 견적 상세 정보를 접어 본문에 높이를 넘긴다(가격 레일은 그대로 남는다).
setShowHeaderCards(false);
if (tab.id === 'chat' && serverSessions.length > 0 && !selectedSessionId) {
setSelectedSessionId(serverSessions[0].session_id);
}
}}
className={`flex items-center gap-2 py-4 px-3 text-xs tracking-tight font-semibold border-b-2 transition-all cursor-pointer ${
@@ -323,7 +335,9 @@ export function QuotationDetailSheet({
onOpenChat={goToChat}
onNotifyAll={() => onNotify(qtId)}
onNotifyOne={(sessionId) => onNotifySession(sessionId, qtId)}
onAward={(supplierId, supplierName) => onAward(qtId, supplierId, supplierName)}
onAward={(supplierId, supplierName, contractPrice, contractNote) =>
onAward(qtId, supplierId, supplierName, contractPrice, contractNote)
}
/>
)}
@@ -134,9 +134,18 @@ export function useQuotations(params: ListQuotationsParams) {
// 개찰(낙찰자 미정 마감) 견적을 담당자가 직접 낙찰 처리 → 서버 award_quotation(close_reason→낙찰 + 낙찰자 박제 + 작성자 알림).
// 성공 시 단건 견적·세션·알림 목록 재조회로 결과밴드('개찰'→'낙찰')와 알림함을 동기화.
const awardQuotation = async (qtId: string, winnerSupplierId: string, winnerName: string): Promise<boolean> => {
const awardQuotation = async (
qtId: string,
winnerSupplierId: string,
winnerName: string,
contractPrice: number,
contractNote?: string,
): Promise<boolean> => {
try {
const res = await awardQuotationMutation.mutateAsync({ qtId, data: { winner_supplier_id: winnerSupplierId } });
const res = await awardQuotationMutation.mutateAsync({
qtId,
data: { winner_supplier_id: winnerSupplierId, contract_price: contractPrice, contract_note: contractNote || null },
});
if (!res?.result?.success) {
const reason = res?.msg ?? res?.result?.desc ?? '서버 오류';
const code = res?.result?.code;
@@ -244,6 +244,7 @@ export type SessionView = {
status: number;
target_price: number;
anchoring_price: number;
done_ceiling_price: number; // 완료 상한가(원) — 생성 시 박제값. 0=미박제(구 견적)
bid_price: number | null;
bid_at: string;
reject_reason: string | null;
@@ -283,14 +284,95 @@ export type QuotationResultView = {
savingsRate: number | null;
};
// 계약 기준가 — 타결했으면 투찰가, 협상이 거부로 끝났으면 그때 써낸 공급 희망 가격.
// 결렬 건도 최종 제출가로 계약을 진행하므로 낙찰 후보·결과 표기가 같은 기준을 본다.
// 타결 상한가 — 합의가가 이 금액 이하면 타결, 초과하면 결렬.
// 세션 박제값(생성 시점)이 정본이다. 생성 후 세팅이 바뀌어도 협상은 박제값으로 판정하기 때문.
// 박제 이전 견적은 값이 0/없음이라 같은 식(목표가×(1+율/1000), 10원 반올림)으로 환산해 보여준다.
export function ceilingPriceOf(session: SessionView | undefined, ceilingRate: number): number | null {
if (session?.done_ceiling_price) return session.done_ceiling_price;
if (!session?.target_price) return null;
return Math.round((session.target_price * (1000 + ceilingRate)) / 10000) * 10;
}
export type PriceRailView = {
oneToOne: boolean;
/** 1:1 전용 — 앵커링가는 (상품×공급사)마다 달라 1:N 에는 견적 대표값이 없다(협상현황 표의 협력사별 컬럼으로 본다). */
anchorPrice: number | null;
/** 1:N 전용 — 가격을 제출한 협력사 수 / 초청 협력사 수. */
bidCount: number;
supplierCount: number;
targetPrice: number | null;
ceilingPrice: number | null;
ceilingRate: number; // ‰
/** 마지막 칸 — 상태에 따라 낙찰가 / 최저 투찰가 / 현재 제시가로 바뀐다. */
resultLabel: string;
resultPrice: number | null;
resultBadge: string | null;
savings: number | null;
savingsRate: number | null;
outcome: ChainRoundState;
};
// 헤더 가격 레일 파생. 칸 수는 항상 넷이라 상태가 바뀌어도 화면이 흔들리지 않는다.
export function buildPriceRail(
q: QuotationData,
sessions: SessionView[],
ceilingRate: number,
): PriceRailView {
const r = buildQuotationResult(q, sessions);
const oneToOne = is1v1(q.type);
// 목표가·상한가는 상품 단위(1견적=1상품)라 대표 세션 하나로 읽는다. 앵커는 공급사 단위라 1:1 에서만.
const rep = sessions.find((s) => s.target_price > 0) ?? sessions[0];
const priced = sessions.map(awardPrice).filter((v): v is number => v != null);
const resultLabel =
r.outcome === 'awarded' ? '낙찰가'
: r.outcome === 'opened' ? '최저 투찰가'
: oneToOne ? '현재 제시가' : '현재 최저 투찰가';
const resultBadge =
r.outcome === 'awarded' ? null
: r.outcome === 'opened' ? '낙찰자 미정'
: '협상 중';
return {
oneToOne,
anchorPrice: oneToOne ? (rep?.anchoring_price ?? null) : null,
bidCount: priced.length,
supplierCount: sessions.length,
targetPrice: r.targetPrice,
ceilingPrice: ceilingPriceOf(rep, ceilingRate),
ceilingRate,
resultLabel,
resultPrice: r.outcome === 'awarded' ? r.winnerPrice : r.lowestBid,
resultBadge,
// 절감은 낙찰 확정 건만 — 진행 중 잠정 최저가로 절감을 말하면 나중에 뒤집힌다.
savings: r.outcome === 'awarded' ? r.savings : null,
savingsRate: r.outcome === 'awarded' ? r.savingsRate : null,
outcome: r.outcome,
};
}
// 협력사가 시스템에 제출한 가격 — 타결했으면 투찰가, 거부로 끝났으면 그때 써낸 공급 희망 가격.
// 직접 낙찰의 계약가 기본값·최저가 추천에 쓴다. 확정 계약가는 contractPrice 를 본다.
export function awardPrice(s: SessionView): number | null {
if (s.status === SessionStatus.DONE && s.bid_price != null) return s.bid_price;
if (s.status === SessionStatus.REJECTED && s.reject_price != null) return s.reject_price;
return null;
}
// 오프라인 협상 결과로 담당자가 확정한 계약가(sessions.custom.offline_award).
// 결렬·미응찰 건을 오프라인으로 다시 협상해 낙찰시킨 경우라 협력사 제출가와 다를 수 있다.
export function offlineAward(s: SessionView): { price: number; note: string; at: string } | null {
const raw = s.custom?.offline_award as { price?: unknown; note?: unknown; at?: unknown } | undefined;
const price = Number(raw?.price);
if (!raw || !Number.isFinite(price) || price <= 0) return null;
return { price, note: String(raw.note ?? ''), at: String(raw.at ?? '') };
}
// 확정 계약가 — 담당자가 넣은 값이 있으면 그것, 없으면 협력사 제출가. 결과 표기·절감 계산의 기준.
export function contractPrice(s: SessionView): number | null {
return offlineAward(s)?.price ?? awardPrice(s);
}
export function buildQuotationResult(q: QuotationData, sessions: SessionView[]): QuotationResultView {
const winnerId = q.preferred_sp_id ?? null;
const winnerSession = winnerId ? sessions.find((s) => s.supplier_id === winnerId) ?? null : null;
@@ -299,7 +381,8 @@ export function buildQuotationResult(q: QuotationData, sessions: SessionView[]):
const bids = sessions.map(awardPrice).filter((v): v is number => v != null);
const lowestBid = bids.length ? Math.min(...bids) : null;
const highestBid = bids.length ? Math.max(...bids) : null;
const winnerPrice = (winnerSession ? awardPrice(winnerSession) : null) ?? lowestBid;
// 낙찰가는 확정 계약가 기준 — 오프라인으로 다시 협상해 낙찰한 건은 제출가와 다르다.
const winnerPrice = (winnerSession ? contractPrice(winnerSession) : null) ?? lowestBid;
const provisional = !winnerSession;
const sessionTarget =
@@ -392,6 +475,7 @@ export function mapServerSessionView(sd: SessionData, partners: Partner[], produ
status: sd.status,
target_price: sd.target_price ?? 0,
anchoring_price: sd.anchoring_price ?? 0,
done_ceiling_price: sd.done_ceiling_price ?? 0,
bid_price: sd.bid_price ?? null,
bid_at: sd.bid_at ? fmtDateTime(sd.bid_at) : '-',
reject_reason: sd.reject_reason ?? null,
@@ -34,7 +34,14 @@ export function StatisticsView({ data }: { data: StatData }) {
delta={{ text: `${signedWonCompact(k.savingsDeltaMoM)} 전월비`, good: k.savingsDeltaMoM >= 0 }}
/>
<StatTile label="평균 절감률" value={pct(k.savingsRate)} icon={Percent} tone="emerald" />
<StatTile label="낙찰률" value={pct(k.awardRate)} icon={Award} tone="blue" />
<StatTile
label="낙찰률"
value={pct(k.awardRate)}
icon={Award}
tone="blue"
// 오프라인으로 다시 협상해 담당자가 반영한 건수 — 절감액엔 포함되지만 AI 협상 성과와 섞이지 않게 따로 짚는다.
delta={k.offlineAwardCount > 0 ? { text: `오프라인 반영 ${k.offlineAwardCount}건` } : undefined}
/>
<StatTile label="평균 앵커 도달률" value={pct(k.anchorReachRate)} icon={Target} tone="purple" />
<StatTile label="마감 견적" value={`${k.closedCount}건`} icon={CircleCheckBig} tone="zinc" />
<StatTile label="평균 재견적 라운드" value={k.regenAvgRound.toFixed(1)} icon={RefreshCw} tone="amber" />
@@ -18,6 +18,7 @@ function mapScope(s?: ApiScope): StatData {
closedCount: k.closed_count ?? 0,
regenAvgRound: k.regen_avg_round ?? 0,
markupSuppressionRate: k.markup_suppression_rate ?? 0,
offlineAwardCount: k.offline_award_count ?? 0,
},
trend: (s?.trend ?? []).map((t) => ({ month: t.month, savings: t.savings ?? 0, rate: t.rate ?? 0 })),
markupTrend: (s?.markup_trend ?? []).map((t) => ({ month: t.month, rate: t.rate ?? 0 })),
@@ -12,6 +12,7 @@ export interface StatKpi {
closedCount: number; // 마감 견적 수(창)
regenAvgRound: number; // 평균 재견적 라운드(1=재견적 없음)
markupSuppressionRate: number; // 인상억제율(재협상: 직전 라운드 투찰가 대비 이번 투찰가 인하율)
offlineAwardCount: number; // 낙찰 중 오프라인 협상 결과를 담당자가 반영한 건수(절감액엔 포함)
}
export interface MonthPoint {