[feat] negodata/front: 프론트 초기 구축 (Vite+React, orval API 클라이언트, 견적/상품/협력사 페이지)

- 라우팅 react-router v7, 서버상태 TanStack Query
- orval 자동 생성 API 클라이언트(src/api/generated)
- 견적/상품/협력사/견적설정 페이지, shadcn UI, 토큰(tokens.css)
- 실행: 루트 docker compose (front :3001), README 그에 맞게 정리
- AI Studio 스캐폴드 잔재 제거(metadata.json, 중복 DESIGN_TOKENS.md), 타이틀 NegoData, vite.config 죽은코드 제거

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 4.8 committed 2026-06-16 17:18:08 +09:00
1 parent a6731dcb07
commit 87524bf6e8
288 files changed
+26363 -1

No files matched your search

@@ -0,0 +1,257 @@
import { useState } from 'react';
import { X, PlusSquare, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Typography } from '@/components/ui/typography';
import { Input } from '@/components/ui/input';
import type { Product, Partner, QuotationSetting, NegotiationCard } from '../types';
import type { CreateQuotationInput } from '../hooks/useQuotations';
type CreateQuotationWizardProps = {
open: boolean;
products: Product[];
partners: Partner[];
cards: NegotiationCard[];
quotationSettings: QuotationSetting[];
onCreate: (input: CreateQuotationInput) => boolean;
onClose: () => void;
};
export function CreateQuotationWizard({
open,
products,
partners,
cards,
quotationSettings,
onCreate,
onClose,
}: CreateQuotationWizardProps) {
const [step, setStep] = useState(1);
const [title, setTitle] = useState('');
const [type, setType] = useState<'RE_NEGOTIATION' | 'RE_ESTIMATE'>('RE_NEGOTIATION');
const [productId, setProductId] = useState('');
const [selectedPartnerIds, setSelectedPartnerIds] = useState<string[]>([]);
const [dueDate, setDueDate] = useState('2026-06-15T18:00');
const [settingId, setSettingId] = useState(quotationSettings[0]?.qt_setting_id ?? '');
const [selectedCardIds, setSelectedCardIds] = useState<string[]>([]);
if (!open) return null;
const togglePartner = (id: string) =>
setSelectedPartnerIds((prev) =>
prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id],
);
const toggleCard = (id: string) =>
setSelectedCardIds((prev) =>
prev.includes(id) ? prev.filter((c) => c !== id) : [...prev, id],
);
const handleSubmit = () => {
const ok = onCreate({
title,
type,
productId,
partnerIds: selectedPartnerIds,
dueDate,
settingId,
cardIds: selectedCardIds,
});
if (ok) onClose();
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-xl bg-card border border-border rounded-lg shadow-2xl p-6 overflow-hidden animate-scale-up font-mono">
{/* Header */}
<div className="flex items-center justify-between pb-4 border-b border-border">
<div className="flex items-center gap-2">
<PlusSquare className="text-foreground" size={18} />
<span className="text-sm font-bold text-foreground">신규 견적 발의 (단계 {step}/3)</span>
</div>
<button onClick={onClose} className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer">
<X size={18} />
</button>
</div>
{/* Steps indicator */}
<div className="flex items-center justify-between gap-2 py-4 border-b border-border/40 text-[10px] text-muted-foreground">
<span className={`font-semibold ${step >= 1 ? 'text-primary' : ''}`}>1. 기본 등록</span>
<ArrowRight size={10} />
<span className={`font-semibold ${step >= 2 ? 'text-primary' : ''}`}>2. 협력사 선택</span>
<ArrowRight size={10} />
<span className={`font-semibold ${step >= 3 ? 'text-primary' : ''}`}>3. 설정 및 완료</span>
</div>
{/* Step content */}
<div className="my-6 min-h-60 text-xs text-foreground space-y-4">
{step === 1 && (
<div className="space-y-4">
<div className="space-y-1">
<Typography as="label" variant="label">견적건명</Typography>
<Input
id="wizard-title"
type="text"
className="text-xs"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="예: 6월 배터리 원부자재 견적 의뢰"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1">
<Typography as="label" variant="label">유형</Typography>
<select
id="wizard-type"
className="w-full p-2 bg-background border border-border rounded text-xs cursor-pointer"
value={type}
onChange={(e) => setType(e.target.value as 'RE_NEGOTIATION' | 'RE_ESTIMATE')}
>
<option value="RE_NEGOTIATION">재협상</option>
<option value="RE_ESTIMATE">재견적</option>
</select>
</div>
<div className="space-y-1">
<Typography as="label" variant="label">마감기한</Typography>
<input
id="wizard-date"
type="datetime-local"
className="w-full p-2 bg-background border border-border rounded text-xs"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
/>
</div>
</div>
<div className="space-y-1">
<Typography as="label" variant="label">상품</Typography>
<select
id="wizard-product"
className="w-full p-2 bg-background border border-border rounded text-xs cursor-pointer"
value={productId}
onChange={(e) => setProductId(e.target.value)}
>
<option value="">협상 대상 상품을 고르세요...</option>
{products.filter((p) => p.status === 'ACTIVE').map((p) => (
<option key={p.id} value={p.id}>
{p.name} [{p.code}] (기준가: ₩{(p.price ?? 0).toLocaleString()})
</option>
))}
</select>
</div>
</div>
)}
{step === 2 && (
<div className="space-y-3">
<span className="font-semibold text-foreground block">협력사 초청 (다중선택)</span>
<div className="border border-border rounded overflow-hidden max-h-56 overflow-y-auto divide-y divide-border bg-background">
{partners.map((part) => {
const isChecked = selectedPartnerIds.includes(part.id ?? '');
return (
<label
key={part.id}
className="flex items-center justify-between p-3 hover:bg-muted/30 cursor-pointer transition-colors"
>
<div className="flex items-center gap-2.5">
<input
type="checkbox"
checked={isChecked}
onChange={() => togglePartner(part.id ?? '')}
className="accent-primary h-4 w-4"
/>
<div>
<span className="font-semibold text-foreground block">{part.name}</span>
<span className="text-[10px] text-muted-foreground">이메일: {part.managerEmail} · 등급: {part.rank}</span>
</div>
</div>
<span
className={`text-[9px] font-mono px-2 py-0.5 rounded ${
part.priority === 'HIGH' ? 'bg-red-50 text-red-700' : 'bg-zinc-100 text-zinc-600'
}`}
>
{part.priority}
</span>
</label>
);
})}
</div>
</div>
)}
{step === 3 && (
<div className="space-y-4">
<div className="space-y-1 font-mono text-xs">
<Typography as="label" variant="label">적용할 견적 세팅 지정</Typography>
<select
id="wizard-setting-select"
className="w-full p-2 bg-background border border-border rounded text-xs focus:outline-none cursor-pointer"
value={settingId}
onChange={(e) => setSettingId(e.target.value)}
>
{quotationSettings.map((qs) => (
<option key={qs.qt_setting_id} value={qs.qt_setting_id}>
[목표 마진: {qs.target_margin}] {qs.anchoring_value} ({qs.card_use_count})
</option>
))}
</select>
</div>
<div className="space-y-2">
<span className="font-semibold text-foreground block">협상카드 및 와일드카드 선택</span>
<div className="grid grid-cols-2 gap-2 max-h-48 overflow-y-auto">
{cards.filter((c) => !c.isWildcard || c.status === 'ACTIVE').map((card) => {
const isChecked = selectedCardIds.includes(card.id);
return (
<div
key={card.id}
onClick={() => toggleCard(card.id)}
className={`p-2.5 rounded border cursor-pointer transition-all flex items-start gap-2 ${
isChecked ? 'bg-primary/5 border-primary font-bold' : 'bg-background border-border hover:bg-muted/10'
}`}
>
<input type="checkbox" checked={isChecked} readOnly className="accent-primary h-3.5 w-3.5 mt-0.5" />
<div>
<span className="text-[10px] text-muted-foreground font-mono block leading-none">{card.code}</span>
<span className="text-xs text-foreground mt-1 block leading-tight">{card.title}</span>
</div>
</div>
);
})}
</div>
</div>
</div>
)}
</div>
{/* Footer nav */}
<div className="flex justify-between items-center pt-4 border-t border-border mt-6">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => (step === 1 ? onClose() : setStep((prev) => prev - 1))}
>
{step === 1 ? '취소' : '이전 보기'}
</Button>
<div className="flex gap-2">
{step < 3 ? (
<Button type="button" size="sm" onClick={() => setStep((prev) => prev + 1)}>
다음 단계로
</Button>
) : (
<Button type="button" size="sm" onClick={handleSubmit}>
견적 발의 등록
</Button>
)}
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,570 @@
import { useState } from 'react';
import {
StopCircle,
X,
UserCheck,
MessageSquare,
Layers,
Info,
} from 'lucide-react';
import SlateRenderer from '@/components/SlateRenderer';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Typography } from '@/components/ui/typography';
import { Input } from '@/components/ui/input';
import {
type Estimate,
type Product,
type Partner,
type QuotationSetting,
type ChatSession,
type NegotiationCard,
normalizeQuotationStatus,
buildBidSummary,
buildSessions,
buildQuotationCards,
} from '../types';
type DrawerTab = 'status' | 'cards' | 'chat';
type QuotationDetailDrawerProps = {
estimate: Estimate;
products: Product[];
partners: Partner[];
cards: NegotiationCard[];
quotationSettings: QuotationSetting[];
sessions: ChatSession[];
onStop: (id: string, name: string) => void;
onClose: () => void;
};
export function QuotationDetailDrawer({
estimate,
products,
partners,
cards,
quotationSettings,
sessions,
onStop,
onClose,
}: QuotationDetailDrawerProps) {
const [activeTab, setActiveTab] = useState<DrawerTab>('status');
const [selectedChatPartnerId, setSelectedChatPartnerId] = useState<string | null>(
sessions[0]?.id ?? null,
);
const [showHeaderCards, setShowHeaderCards] = useState(true);
const activeProduct = products.find((p) => p.id === estimate.productId) ?? null;
const currentChatSession = sessions.find((s) => s.id === selectedChatPartnerId) || sessions[0];
const selectedSettingObj = quotationSettings.find((qs) => qs.qt_setting_id === estimate.settingApplied);
const bidSummaryObj = buildBidSummary(estimate, partners);
const sessionViews = buildSessions(estimate, sessions, partners, products);
const quotationCardViews = buildQuotationCards(estimate, cards);
// Quotations DDL 표시값
const q_name = estimate.name || estimate.title || '미지정';
const q_number = estimate.number || 'EST-000000-0000';
const q_type = estimate.type || '1:1';
const q_round = estimate.round || 1;
const q_status = estimate.status || '견적생성';
const q_end_time = estimate.end_time || estimate.dueDate || '미지정';
const q_manager_name = estimate.manager_name || '홍길동 파트너';
const q_manager_email = estimate.manager_email || 'gildong@negodata.com';
const q_memo = estimate.memo || '안내사항 없음';
const statusKey = normalizeQuotationStatus(q_status);
const goToChat = (partnerId: string) => {
setSelectedChatPartnerId(partnerId);
setActiveTab('chat');
};
const tabs: { id: DrawerTab; label: string; icon: typeof UserCheck }[] = [
{ id: 'status', label: '협상 현황', icon: UserCheck },
{ id: 'chat', label: '협상 대화', icon: MessageSquare },
{ id: 'cards', label: '협상 카드', icon: Layers },
];
return (
<div className="fixed inset-0 z-40 bg-black/40 backdrop-blur-xs flex justify-end animate-fade-in">
<div className="flex-1 cursor-pointer" onClick={onClose} />
<div className="w-full max-w-5xl bg-card border-l border-border h-full flex flex-col justify-between shadow-2xl overflow-hidden animate-slide-left">
{/* Header */}
<div className="p-6 border-b border-border 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>B2B 견적 상세 // {q_number}</span>
</div>
<Typography variant="h3" className="mt-1">{q_name}</Typography>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => setShowHeaderCards(!showHeaderCards)}
className="flex items-center gap-1.5 px-2.5 py-1.5 bg-muted hover:bg-muted-foreground/15 text-foreground border border-border rounded text-xs font-semibold cursor-pointer transition-colors"
>
<span>{showHeaderCards ? '데이터베이스 매핑 정보 접기 ▲' : '데이터베이스 매핑 정보 펼치기 ▼'}</span>
</button>
{estimate.status === 'ACTIVE' && (
<button
onClick={() => onStop(estimate.id ?? '', q_name)}
className="flex items-center gap-1 px-3 py-1.5 bg-red-600 hover:bg-rose-700 text-white rounded text-xs font-semibold cursor-pointer transition-colors"
>
<StopCircle size={14} />
<span>중지</span>
</button>
)}
<button
onClick={onClose}
className="p-1.5 rounded-full text-muted-foreground hover:bg-muted cursor-pointer"
>
<X size={20} />
</button>
</div>
</div>
{/* DB mapping info cards */}
{showHeaderCards && (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mt-4 text-xs font-mono">
{/* Quotations */}
<div className="p-3 bg-card border border-border/80 rounded shadow-xs space-y-2">
<span className="font-bold text-foreground text-[11px] border-b border-border pb-1 block font-sans">
견적 정보 (quotations)
</span>
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 font-mono text-muted-foreground">
<div>
<span className="text-[10px] block opacity-70">견적명 (name)</span>
<span className="text-foreground font-semibold font-sans">{q_name}</span>
</div>
<div>
<span className="text-[10px] block opacity-70">견적번호 (number)</span>
<span className="text-foreground font-semibold">{q_number}</span>
</div>
<div>
<span className="text-[10px] block opacity-70">유형 (type)</span>
<span className="text-foreground font-semibold">
{q_type === 'RE_NEGOTIATION' ? '재협상 (RE_NEGOTIATION)' : '재견적 (RE_ESTIMATE)'}
</span>
</div>
<div>
<span className="text-[10px] block opacity-70">차수 (round)</span>
<span className="text-foreground font-semibold">{q_round}차 (round)</span>
</div>
<div>
<span className="text-[10px] block opacity-90 font-bold mb-1">견적상태 (status)</span>
<span
className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 text-[11px] font-bold rounded-full border shadow-2xs ${
statusKey === '견적생성'
? 'bg-amber-100 text-amber-800 border-amber-300 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-700/50 animate-pulse'
: statusKey === '견적진행중'
? 'bg-emerald-100 text-emerald-800 border-emerald-300 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-700/50'
: statusKey === '견적마감'
? 'bg-blue-100 text-blue-800 border-blue-300 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-700/50'
: statusKey === '협상보류'
? 'bg-rose-100 text-rose-800 border-rose-300 dark:bg-rose-950/40 dark:text-rose-300 dark:border-rose-700/50'
: 'bg-zinc-100 text-zinc-800 border-zinc-300'
}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${
statusKey === '견적생성'
? 'bg-amber-500'
: statusKey === '견적진행중'
? 'bg-emerald-500'
: statusKey === '견적마감'
? 'bg-blue-500'
: statusKey === '협상보류'
? 'bg-rose-500'
: 'bg-zinc-500'
}`}
/>
{statusKey || q_status}
</span>
</div>
<div>
<span className="text-[10px] block opacity-70">마감시각 (end_time)</span>
<span className="text-foreground font-semibold">{q_end_time}</span>
</div>
<div>
<span className="text-[10px] block opacity-70">담당자 (manager_name)</span>
<span className="text-foreground font-semibold font-sans">{q_manager_name} ({q_manager_email})</span>
</div>
<div>
<span className="text-[10px] block opacity-70">메모 (memo)</span>
<span className="text-foreground font-semibold font-sans truncate block" title={q_memo || ''}>
{q_memo}
</span>
</div>
</div>
</div>
{/* Bid Summary */}
<div className="p-3 bg-card border border-border/80 rounded shadow-xs space-y-2">
<span className="font-bold text-foreground text-[11px] border-b border-border pb-1 block font-sans">
견적 진행상태/결과 (bid_summary)
</span>
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 font-mono text-muted-foreground">
<div>
<span className="text-[10px] block opacity-70">식별자 (bid_summary_id)</span>
<span className="text-foreground font-semibold">{bidSummaryObj.bid_summary_id}</span>
</div>
<div>
<span className="text-[10px] block opacity-70">진행/결과 상태 (status)</span>
<span className="text-foreground font-semibold">{bidSummaryObj.status}</span>
</div>
<div>
<span className="text-[10px] block opacity-70">반복횟수 (qt_iteration)</span>
<span className="text-foreground font-semibold">{bidSummaryObj.qt_iteration}회 (qt_iteration)</span>
</div>
<div>
<span className="text-[10px] block opacity-70">우선협상자 존재여부 (has_preferred)</span>
<span className={`text-foreground font-semibold ${bidSummaryObj.has_preferred ? 'text-emerald-600 font-bold' : ''}`}>
{bidSummaryObj.has_preferred ? '존재 (true)' : '미존재 (false)'}
</span>
</div>
<div className="col-span-2">
<span className="text-[10px] block opacity-70">우선협상자명 (preferred_sp_name)</span>
<span className="text-foreground font-semibold font-sans">{bidSummaryObj.preferred_sp_name}</span>
</div>
<div className="col-span-2">
<span className="text-[10px] block opacity-70">동가입찰정보 (equal_data)</span>
<code className="text-foreground font-semibold bg-muted/60 p-1 rounded text-[10px] block overflow-x-auto whitespace-pre">
{bidSummaryObj.equal_data}
</code>
</div>
</div>
</div>
{/* Quotation Settings */}
<div className="p-3 bg-card border border-border/80 rounded shadow-xs space-y-2">
<span className="font-bold text-foreground text-[11px] border-b border-border pb-1 block font-sans">
견적 세팅 (quotation_settings)
</span>
{selectedSettingObj ? (
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5 font-mono text-muted-foreground">
<div>
<span className="text-[10px] block opacity-70">세팅 아이디 (qt_setting_id)</span>
<span className="text-foreground font-semibold text-[10px] truncate block" title={selectedSettingObj.qt_setting_id}>
{selectedSettingObj.qt_setting_id}
</span>
</div>
<div>
<span className="text-[10px] block opacity-70">유저 아이디 (user_id)</span>
<span className="text-foreground font-semibold text-[10px] truncate block" title={selectedSettingObj.user_id}>
{selectedSettingObj.user_id}
</span>
</div>
<div>
<span className="text-[10px] block opacity-70">목표 마진율 (target_margin)</span>
<span className="text-foreground font-bold text-emerald-600 dark:text-emerald-400 font-sans">{selectedSettingObj.target_margin}</span>
</div>
<div>
<span className="text-[10px] block opacity-70">앵커링 설정 값 (anchoring_value)</span>
<span className="text-foreground font-semibold font-sans">{selectedSettingObj.anchoring_value}</span>
</div>
<div className="col-span-2 col-start-1">
<span className="text-[10px] block opacity-70">카드 사용 횟수 (card_use_count)</span>
<span className="text-foreground font-semibold">{selectedSettingObj.card_use_count}</span>
</div>
</div>
) : (
<div className="text-muted-foreground py-6 text-center">적용된 견적 세팅이 비어있습니다.</div>
)}
</div>
</div>
)}
</div>
{/* Tabs */}
<div className="border-b border-border bg-background px-6">
<div className="flex gap-4">
{tabs.map((tab) => {
const Icon = tab.icon;
return (
<button
key={tab.id}
onClick={() => {
setActiveTab(tab.id);
if (tab.id === 'chat' && sessions.length > 0 && !selectedChatPartnerId) {
setSelectedChatPartnerId(sessions[0].id);
}
}}
className={`flex items-center gap-2 py-4 px-3 text-xs tracking-tight font-semibold border-b-2 transition-all cursor-pointer ${
activeTab === tab.id
? 'border-primary text-primary font-bold'
: 'border-transparent text-muted-foreground hover:text-foreground'
}`}
>
<Icon size={14} />
<span>{tab.label}</span>
</button>
);
})}
</div>
</div>
{/* Tab content */}
<div className="flex-1 p-6 overflow-y-auto bg-background/50">
{/* Tab: Sessions Status */}
{activeTab === 'status' && (
<div className="space-y-4">
<div className="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]">
<TableHeader className="bg-muted text-muted-foreground text-[10px] border-b border-border">
<TableRow>
<TableHead className="p-3 font-semibold">세션 ID</TableHead>
<TableHead className="p-3 font-semibold font-sans">협력사</TableHead>
<TableHead className="p-3 font-semibold font-sans">상품</TableHead>
<TableHead className="p-3 font-semibold text-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>
<TableHead className="p-3 font-semibold font-sans">거절사유</TableHead>
<TableHead className="p-3 font-semibold text-right">거절가격</TableHead>
<TableHead className="p-3 font-semibold font-sans">거절배송방식</TableHead>
</TableRow>
</TableHeader>
<TableBody className="divide-y divide-border">
{sessionViews.map((sess) => (
<TableRow key={sess.session_id} className="hover:bg-muted/30 transition-colors text-[11px]">
<TableCell className="p-3 text-muted-foreground font-mono">{sess.session_id}</TableCell>
<TableCell className="p-3 font-bold text-foreground font-sans">
<div className="flex items-center gap-2">
<span>{sess.supplier_name}</span>
<button
onClick={() => goToChat(sess.supplier_id)}
title="협상 대화방으로 이동"
className="p-1 hover:bg-primary/10 rounded text-primary hover:text-primary/80 transition-colors cursor-pointer"
>
<MessageSquare size={13} />
</button>
</div>
</TableCell>
<TableCell className="p-3 font-semibold font-sans">{sess.item_name}</TableCell>
<TableCell className="p-3 text-center">
<span
className={`inline-flex px-2 py-0.5 rounded-full text-[10px] font-bold ${
sess.status === '협상종료' || sess.status === 'COMPLETED'
? 'bg-blue-100 text-blue-800 dark:bg-blue-950/20 dark:text-blue-300'
: sess.status === '협상거부' || sess.status === 'REJECTED'
? 'bg-red-100 text-red-800 dark:bg-red-950/20 dark:text-red-300'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/20 dark:text-emerald-300'
}`}
>
{sess.status}
</span>
</TableCell>
<TableCell className="p-3 text-right font-bold text-muted-foreground">
₩{sess.target_price?.toLocaleString() || '-'}
</TableCell>
<TableCell className="p-3 text-right font-bold text-foreground">
{sess.bid_price ? `₩${sess.bid_price.toLocaleString()}` : '-'}
</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>
<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>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
)}
{/* Tab: Quotation Cards */}
{activeTab === 'cards' && (
<div className="space-y-4">
<div className="flex items-center gap-2 p-3 bg-muted/40 rounded border border-border text-xs text-muted-foreground">
<Info size={14} />
<span>이 견적서에서 사용할 수 있는 협상카드 리스트입니다.</span>
</div>
<div className="border border-border rounded-lg bg-card overflow-hidden">
<Table className="w-full text-left text-xs border-collapse font-mono">
<TableHeader className="bg-muted text-muted-foreground text-[10px] border-b border-border">
<TableRow>
<TableHead className="p-3 font-semibold">세션 카드 ID</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">
{quotationCardViews.length > 0 ? (
quotationCardViews.map((qc) => (
<TableRow key={qc.session_card_id} className="hover:bg-muted/30 transition-colors text-[11px]">
<TableCell className="p-3 text-muted-foreground">{qc.session_card_id}</TableCell>
<TableCell className="p-3 text-foreground font-sans font-semibold">{qc.card_name}</TableCell>
<TableCell className="p-3">
<span
className={`inline-flex px-2 py-0.5 rounded text-[10px] font-bold ${
qc.type === '와일드 카드'
? 'bg-amber-100 text-amber-800 dark:bg-amber-950/20 dark:text-amber-300'
: 'bg-zinc-100 text-zinc-800 dark:bg-zinc-800/40 dark:text-zinc-300'
}`}
>
{qc.type}
</span>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={3} className="p-12 text-center text-muted-foreground">
해당 견적에 사용할 수 있는 카드가 매핑되지 않습니다.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</div>
)}
{/* Tab: Chat */}
{activeTab === 'chat' && (
<div className="h-[500px] border border-border rounded-lg overflow-hidden bg-card flex">
{/* Sessions list */}
<div className="w-1/3 border-r border-border bg-muted/20 flex flex-col justify-between">
<div className="p-3 border-b border-border bg-muted/40 font-mono text-[10px] text-muted-foreground uppercase">
참여자 협력사 리스트
</div>
<div className="flex-1 overflow-y-auto divide-y divide-border font-sans">
{sessions.map((sess) => {
const isSelected = sess.id === selectedChatPartnerId;
return (
<button
key={sess.id}
onClick={() => setSelectedChatPartnerId(sess.id)}
className={`w-full text-left p-3 flex flex-col justify-between transition-colors cursor-pointer ${
isSelected ? 'bg-primary/5 border-l-4 border-primary' : 'hover:bg-muted/30'
}`}
>
<div className="flex items-center justify-between">
<span className="font-bold text-foreground text-xs">{sess.partnerName}</span>
<span
className={`text-[9px] font-bold px-1.5 py-0.5 rounded ${
sess.status === 'REJECTED' || sess.status === '협상거부'
? 'bg-rose-100 text-rose-800 dark:bg-rose-950/30 dark:text-rose-300'
: sess.status === 'COMPLETED' || sess.status === '협상종료'
? 'bg-blue-100 text-blue-800 dark:bg-blue-950/30 dark:text-blue-300'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-300'
}`}
>
{sess.status}
</span>
</div>
<div className="flex items-center justify-between text-[10px] font-mono text-muted-foreground mt-2">
<span>최종 제의</span>
<span className="font-bold text-foreground">₩{sess.currentBid.toLocaleString()}</span>
</div>
</button>
);
})}
</div>
</div>
{/* Chat zone */}
<div className="flex-1 flex flex-col bg-background justify-between">
<div className="p-3 bg-muted/30 border-b border-border text-xs flex items-center justify-between font-mono">
<div className="text-muted-foreground">
채널: <strong className="text-foreground">{currentChatSession?.partnerName}</strong>
</div>
<div className="text-xs text-muted-foreground">
기록: <span className="font-semibold text-foreground">{currentChatSession?.messages.length}</span> 세션전화
</div>
</div>
<div className="flex-1 p-4 overflow-y-auto space-y-4">
{currentChatSession ? (
currentChatSession.messages.map((msg) => {
const isBot = msg.sender === 'BOT';
const isSystem = msg.sender === 'SYSTEM';
if (isSystem) {
return (
<div key={msg.id} className="flex justify-center my-3">
<span className="px-3 py-1 bg-muted border border-border text-[10px] text-muted-foreground rounded font-mono uppercase tracking-wider">
{msg.content}
</span>
</div>
);
}
return (
<div
key={msg.id}
className={`flex items-start gap-2.5 max-w-[85%] ${isBot ? 'mr-auto' : 'ml-auto flex-row-reverse'}`}
>
<div
className={`h-7 w-7 rounded-sm flex items-center justify-center text-[10px] font-bold uppercase ${
isBot ? 'bg-secondary text-secondary-foreground border border-border' : 'bg-primary text-primary-foreground'
}`}
>
{isBot ? 'BOT' : 'VN'}
</div>
<div className="space-y-1">
<div className={`text-[10px] text-muted-foreground font-mono flex items-center gap-1.5 ${isBot ? '' : 'justify-end'}`}>
<span>{isBot ? 'Negosium AI Bot' : currentChatSession.partnerName}</span>
<span>·</span>
<span>{msg.timestamp}</span>
</div>
<div
className={`p-3 rounded-md border text-xs shadow-xs ${
isBot ? 'bg-secondary border-border text-foreground' : 'bg-primary border-transparent text-primary-foreground'
}`}
>
{msg.editorScript ? (
<SlateRenderer
nodes={msg.editorScript}
variables={{
partner_name: currentChatSession.partnerName,
target_price: activeProduct ? Math.round((activeProduct.price ?? 0) * 0.92) : 1000000,
product_name: activeProduct?.name ?? '해당 배터리 조달품',
}}
/>
) : (
<Typography variant="body" className="whitespace-pre-line leading-relaxed">{msg.content}</Typography>
)}
</div>
</div>
</div>
);
})
) : (
<div className="h-full flex items-center justify-center text-muted-foreground font-mono text-xs">
선택된 대화 채널 데이터가 기록되지 않았습니다.
</div>
)}
</div>
<div className="p-3 border-t border-border bg-muted/20 flex gap-2">
<Input
type="text"
disabled
placeholder="이 대화방은 입찰 참여 세션 기록이므로 정독 전용입니다."
className="flex-1 text-xs text-muted-foreground"
/>
<button
disabled
className="py-1.5 px-3 bg-muted text-muted-foreground text-xs rounded border border-border cursor-not-allowed"
>
전송
</button>
</div>
</div>
</div>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,124 @@
import { useState } from 'react';
import { Settings, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Typography } from '@/components/ui/typography';
import { Input } from '@/components/ui/input';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import type { QuotationSetting } from '../types';
import type { SettingInput } from '../hooks/useQuotations';
type QuotationSettingsModalProps = {
open: boolean;
settings: QuotationSetting[];
onAdd: (input: SettingInput) => boolean;
onDelete: (id: string) => void;
onClose: () => void;
};
export function QuotationSettingsModal({
open,
settings,
onAdd,
onDelete,
onClose,
}: QuotationSettingsModalProps) {
const [targetMargin, setTargetMargin] = useState('');
const [anchoringValue, setAnchoringValue] = useState('');
const [cardUseCount, setCardUseCount] = useState('');
if (!open) return null;
const handleAdd = (e: React.FormEvent) => {
e.preventDefault();
const ok = onAdd({ targetMargin, anchoringValue, cardUseCount });
if (ok) {
setTargetMargin('');
setAnchoringValue('');
setCardUseCount('');
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs">
<div className="w-full max-w-2xl bg-card border border-border rounded-lg shadow-2xl p-6 overflow-hidden animate-scale-up font-mono text-xs">
<div className="flex items-center justify-between pb-4 border-b border-border mb-4">
<div className="flex items-center gap-2">
<Settings className="text-muted-foreground" size={16} />
<Typography variant="h3">견적 세팅 등록 및 관리</Typography>
</div>
<button onClick={onClose} className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer">
<X size={18} />
</button>
</div>
<div className="space-y-6">
{/* Current settings */}
<div>
<span className="font-bold text-foreground block mb-2 text-xs">등록된 견적 세팅 목록</span>
<div className="border border-border rounded overflow-hidden max-h-40 overflow-y-auto">
<Table className="w-full text-left font-mono text-[11px] divide-y divide-border">
<TableHeader className="bg-muted text-muted-foreground">
<TableRow>
<TableHead className="p-2">목표 마진율</TableHead>
<TableHead className="p-2">앵커링 설정 방식</TableHead>
<TableHead className="p-2">카드 사용 횟수</TableHead>
<TableHead className="p-2 text-center w-12">삭제</TableHead>
</TableRow>
</TableHeader>
<TableBody className="divide-y divide-border bg-background">
{settings.map((qs) => (
<TableRow key={qs.qt_setting_id} className="hover:bg-muted/30">
<TableCell className="p-2 font-bold text-primary">{qs.target_margin}</TableCell>
<TableCell className="p-2 text-foreground">{qs.anchoring_value}</TableCell>
<TableCell className="p-2 text-muted-foreground">{qs.card_use_count}</TableCell>
<TableCell className="p-2 text-center">
<button
type="button"
onClick={() => onDelete(qs.qt_setting_id)}
className="text-red-500 hover:text-red-700 font-bold px-1.5 py-0.5 rounded hover:bg-red-50"
>
삭제
</button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
{/* Add form */}
<form onSubmit={handleAdd} className="space-y-3 pt-4 border-t border-border/60">
<span className="font-bold text-foreground block text-xs">신규 견적 세팅 추가</span>
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
<div className="space-y-1">
<Typography as="label" variant="muted" className="text-[10px] font-semibold">목표 마진율 (%)</Typography>
<Input type="text" value={targetMargin} onChange={(e) => setTargetMargin(e.target.value)} placeholder="예: 12%" />
</div>
<div className="space-y-1">
<Typography as="label" variant="muted" className="text-[10px] font-semibold">앵커링 설정 방식</Typography>
<Input type="text" value={anchoringValue} onChange={(e) => setAnchoringValue(e.target.value)} placeholder="예: 최초 즉각 앵커링" />
</div>
<div className="space-y-1">
<Typography as="label" variant="muted" className="text-[10px] font-semibold">카드 사용 횟수</Typography>
<Input type="text" value={cardUseCount} onChange={(e) => setCardUseCount(e.target.value)} placeholder="예: 3회 제한" />
</div>
</div>
<div className="flex justify-end pt-2">
<Button type="submit" size="sm">새 세팅 추가</Button>
</div>
</form>
</div>
{/* Footer */}
<div className="pt-4 border-t border-border mt-6 flex justify-end">
<Button type="button" variant="outline" size="sm" onClick={onClose}>닫기</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,139 @@
import { Eye, StopCircle, Clock, Building2 } from 'lucide-react';
import { DataTable } from '@/components/ui/data-table';
import { type Estimate, type Product, normalizeQuotationStatus } from '../types';
type QuotationTableProps = {
data: Estimate[];
products: Product[];
onOpenDetail: (id: string) => void;
onStop: (id: string, title: string) => void;
};
const statusBadgeClass = (status?: string | null) => {
switch (normalizeQuotationStatus(status)) {
case '견적생성':
return 'bg-yellow-50 text-yellow-700 border-yellow-300 animate-pulse';
case '견적진행중':
return 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/25 dark:text-emerald-400 border-emerald-300/40';
case '견적마감':
return 'bg-blue-50 text-blue-700 border-blue-300';
case '협상보류':
return 'bg-red-50 text-red-700 border-red-300';
default:
return 'bg-zinc-100 text-zinc-600';
}
};
export function QuotationTable({ data, products, onOpenDetail, onStop }: QuotationTableProps) {
return (
<DataTable
data={data}
rowKey={(est) => est.id ?? ''}
onRowClick={(est) => onOpenDetail(est.id ?? '')}
empty="진행 중인 전자 견적 및 자동 협상 계약 내역이 존재하지 않습니다."
columns={[
{
header: '견적건명',
cell: (est) => {
const product = products.find((p) => p.id === est.productId);
return (
<div>
<span className="font-bold text-sm text-foreground hover:underline cursor-pointer block">
{est.title}
</span>
<span className="text-[10px] text-muted-foreground font-mono flex items-center gap-1.5 mt-0.5">
<Building2 size={10} />
대상 상품: {product ? product.name : '확인 불가'} (₩{(product?.price ?? 0).toLocaleString()})
</span>
</div>
);
},
},
{
header: '견적번호',
cellClassName: 'font-mono text-muted-foreground',
cell: (est) => est.number,
},
{
header: '유형',
align: 'center',
cell: (est) => (
<span
className={`px-2 py-0.5 rounded-full text-[9px] font-bold ${
est.type === 'RE_NEGOTIATION'
? 'bg-neutral-900 text-white dark:bg-zinc-100 dark:text-black'
: 'bg-zinc-100 text-zinc-900 dark:bg-zinc-800 dark:text-zinc-200'
}`}
>
{est.type === 'RE_NEGOTIATION' ? '재협상' : '재견적'}
</span>
),
},
{
header: '차수',
align: 'center',
cellClassName: 'font-bold font-mono text-sm',
cell: (est) => `${est.round}차`,
},
{
header: '견적상태',
align: 'center',
cell: (est) => (
<span
className={`inline-flex items-center gap-1 px-2.5 py-0.5 text-[10px] font-semibold rounded-full border ${statusBadgeClass(est.status)}`}
>
{normalizeQuotationStatus(est.status) || est.status}
</span>
),
},
{
header: '마감기한',
cellClassName: 'font-mono text-muted-foreground whitespace-nowrap',
cell: (est) => (
<div className="flex items-center gap-1.5">
<Clock size={12} />
<span>{est.dueDate}</span>
</div>
),
},
{
header: '협력사수',
align: 'center',
cellClassName: 'font-mono font-bold text-foreground',
cell: (est) => `${est.participationCount}개사`,
},
{
header: '관리',
align: 'center',
cell: (est) => (
<div className="flex items-center justify-center gap-2">
<button
onClick={(e) => {
e.stopPropagation();
onOpenDetail(est.id ?? '');
}}
className="flex items-center gap-1 px-2.5 py-1 bg-muted hover:bg-muted-foreground/10 text-[11px] font-semibold border border-border rounded cursor-pointer transition-all"
>
<Eye size={12} />
<span>상세 정보</span>
</button>
{est.status === 'ACTIVE' && (
<button
onClick={(e) => {
e.stopPropagation();
onStop(est.id ?? '', est.title ?? '');
}}
className="p-1 text-red-500 hover:bg-red-50 dark:hover:bg-red-950/20 rounded cursor-pointer"
title="협상 절차 조기 강제중단"
>
<StopCircle size={14} />
</button>
)}
</div>
),
},
]}
/>
);
}
@@ -0,0 +1,29 @@
import { useState } from 'react';
import { type Estimate, normalizeQuotationStatus } from '../types';
// 견적 목록의 검색/상태/유형 필터 state + 파생 결과.
export function useQuotationFilters(quotations: Estimate[]) {
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState('ALL');
const [typeFilter, setTypeFilter] = useState('ALL');
const filtered = quotations.filter((est) => {
const q = search.toLowerCase();
const matchesSearch =
(est.title || '').toLowerCase().includes(q) || (est.number || '').toLowerCase().includes(q);
const matchesStatus =
statusFilter === 'ALL' || normalizeQuotationStatus(est.status) === statusFilter;
const matchesType = typeFilter === 'ALL' || est.type === typeFilter;
return matchesSearch && matchesStatus && matchesType;
});
return {
search,
setSearch,
statusFilter,
setStatusFilter,
typeFilter,
setTypeFilter,
filtered,
};
}
@@ -0,0 +1,228 @@
import { useEffect, useState } from 'react';
import { useListItems } from '@/api/generated/item/item';
import { useListSuppliers } from '@/api/generated/supplier/supplier';
import { useListSettings } from '@/api/generated/quotation-setting/quotation-setting';
import { useListQuotations } from '@/api/generated/quotation/quotation';
import type { ItemResponse } from '@/api/generated/model/itemResponse';
import type { SupplierResponse } from '@/api/generated/model/supplierResponse';
import type { QuotationSettingResponse } from '@/api/generated/model/quotationSettingResponse';
import type { QuotationResponse } from '@/api/generated/model/quotationResponse';
import { showToast } from '@/lib/notify';
import type { Estimate, QuotationSetting, ChatSession, NegotiationCard, Product } from '@/types';
import { unwrap, mapItem, mapSupplier, mapSetting, mapQuotation } from '../types';
export type CreateQuotationInput = {
title: string;
type: 'RE_NEGOTIATION' | 'RE_ESTIMATE';
productId: string;
partnerIds: string[];
dueDate: string; // datetime-local 원본값
settingId: string;
cardIds: string[];
};
export type SettingInput = {
targetMargin: string;
anchoringValue: string;
cardUseCount: string;
};
// 견적 화면 데이터 허브.
// 상품/협력사/세팅/견적은 서버(orval)에서 읽고, 견적·세팅·채팅은 로컬 state로 낙관적 갱신한다.
// (협상카드 카탈로그/채팅은 백엔드 미연동 → 빈 상태)
export function useQuotations() {
const itemsQuery = useListItems({ size: 100 });
const suppliersQuery = useListSuppliers({ size: 100 });
const settingsQuery = useListSettings();
const quotationsQuery = useListQuotations(undefined);
const products = (unwrap<{ items?: ItemResponse[] }>(itemsQuery.data)?.items ?? []).map(mapItem);
const partners = (unwrap<{ suppliers?: SupplierResponse[] }>(suppliersQuery.data)?.suppliers ?? []).map(mapSupplier);
const [quotationSettings, setQuotationSettings] = useState<QuotationSetting[]>([]);
useEffect(() => {
const s = unwrap<{ settings?: QuotationSettingResponse[] }>(settingsQuery.data)?.settings;
if (s) setQuotationSettings(s.map(mapSetting));
}, [settingsQuery.data]);
const [quotations, setQuotations] = useState<Estimate[]>([]);
useEffect(() => {
const qs = unwrap<{ quotations?: QuotationResponse[] }>(quotationsQuery.data)?.quotations;
if (qs) setQuotations(qs.map(mapQuotation));
}, [quotationsQuery.data]);
// 협상카드 카탈로그/채팅은 아직 백엔드 미연동 → 빈 상태.
const [cards] = useState<NegotiationCard[]>([]);
const [chatSessions, setChatSessions] = useState<Record<string, ChatSession[]>>({});
// '견적생성(PROCESSING)' 견적을 3초 후 '견적진행중'으로 전이시키는 폴링 시뮬레이션.
useEffect(() => {
const processingItem = quotations.find(
(est) => est.status === 'PROCESSING' || est.status === '견적생성',
);
if (!processingItem) return;
const timer = setTimeout(() => {
setQuotations((prev) =>
prev.map((est) => {
if (est.status === 'PROCESSING' || est.status === '견적생성') {
showToast(`[${est.title}] 견적 절차가 개시되었습니다. 파트너 입찰 채널이 활성화되었습니다.`, 'success');
return { ...est, status: '견적진행중' };
}
return est;
}),
);
}, 3000);
return () => clearTimeout(timer);
}, [quotations]);
// 협상 강제중단 → '협상보류'.
const stopNegotiation = (id: string, name: string) => {
if (!confirm(`현재 입찰 중인 [${name}] 단가 협상 절차를 즉시 조기 중단(강제종료)하시겠습니까?`)) return;
setQuotations((prev) => prev.map((e) => (e.id === id ? { ...e, status: '협상보류' } : e)));
showToast("해당 협상이 관리자에 의하여 '협상보류' 상태로 지정되었습니다.", 'info');
};
// 견적 세팅 추가. 검증 실패 시 toast 후 false.
const addSetting = (input: SettingInput): boolean => {
if (!input.targetMargin.trim() || !input.anchoringValue.trim() || !input.cardUseCount.trim()) {
showToast('모든 세팅 항목을 입력해야 합니다.', 'error');
return false;
}
const newSetting: QuotationSetting = {
qt_setting_id: `set-${Date.now()}`,
user_id: 'user-777-uuid',
target_margin: input.targetMargin.includes('%') ? input.targetMargin : `${input.targetMargin}%`,
anchoring_value: input.anchoringValue,
card_use_count: input.cardUseCount.includes('회') ? input.cardUseCount : `${input.cardUseCount}회`,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
deleted: false,
};
setQuotationSettings((prev) => [...prev, newSetting]);
showToast('새 견적 세팅 템플릿이 추가되었습니다.', 'success');
return true;
};
// 견적 세팅 삭제(최소 1개 유지).
const deleteSetting = (id: string) => {
if (quotationSettings.length <= 1) {
showToast('최소 한 개의 세팅은 유지되어야 합니다.', 'error');
return;
}
if (!confirm('선택한 견적 세팅을 삭제하시겠습니까?')) return;
setQuotationSettings((prev) => prev.filter((qs) => qs.qt_setting_id !== id));
showToast('세팅이 삭제되었습니다.', 'info');
};
// 신규 견적 발의 — 견적 레코드 + 협력사별 채팅 세션을 생성. 검증 실패 시 toast 후 false.
const createQuotation = (input: CreateQuotationInput): boolean => {
if (!input.title.trim()) {
showToast('견적 건명을 올바르게 작성해 주세요.', 'error');
return false;
}
if (!input.productId) {
showToast('협상 대상 품목을 지정하지 않았습니다.', 'error');
return false;
}
if (input.partnerIds.length === 0) {
showToast('최소 한 곳 이상의 벤더사(참여 협력사)를 선정해 주세요.', 'error');
return false;
}
const targetProduct = products.find((p) => p.id === input.productId);
const estId = `est-${Date.now()}`;
const newEstNumber = `EST-202606-${Math.floor(1000 + Math.random() * 9000)}`;
const newQuotationRecord: Estimate = {
id: estId,
title: input.title,
number: newEstNumber,
type: input.type,
round: 1,
status: '견적생성',
dueDate: input.dueDate.replace('T', ' '),
participationCount: input.partnerIds.length,
productId: input.productId,
partnerIds: input.partnerIds,
settingApplied: input.settingId,
usedCardIds: input.cardIds,
winnerPartnerId: undefined,
finalPrice: undefined,
isEqualPrice: false,
};
const generatedSessions: ChatSession[] = input.partnerIds.map((pId) =>
buildInitialSession(pId, estId, partners, targetProduct),
);
setChatSessions((prev) => ({ ...prev, [estId]: generatedSessions }));
setQuotations((prev) => [newQuotationRecord, ...prev]);
showToast(`신규 견정 제안서[${input.title}]가 발행되었습니다. 협상 세션 수립 중... (폴링 가동)`, 'info');
return true;
};
return {
products,
partners,
cards,
quotations,
quotationSettings,
chatSessions,
stopNegotiation,
addSetting,
deleteSetting,
createQuotation,
};
}
// 참여 협력사 1곳에 대한 초기 채팅 세션(시스템/봇/협력사 메시지) 생성.
function buildInitialSession(
pId: string,
estId: string,
partners: ReturnType<typeof mapSupplier>[],
targetProduct: Product | undefined,
): ChatSession {
const partnerObj = partners.find((part) => part.id === pId);
const partnerName = partnerObj?.name ?? '미지정 파트너';
const initialPartnerBid = Math.round((targetProduct?.price || 1000000) * (0.95 + Math.random() * 0.1));
const targetNegoPrice = Math.round((targetProduct?.price || 1000000) * 0.9);
return {
id: pId,
partnerName,
status: 'NEGOTIATING',
currentBid: initialPartnerBid,
bidTime: '2026-06-11 01:10',
messages: [
{
id: `msg-${estId}-sys`,
sender: 'SYSTEM',
timestamp: '2026-06-11 01:00',
content: `사전에 조율된 [${targetProduct?.name}] 입찰 참여 세션이 개시되었습니다.`,
},
{
id: `msg-${estId}-bot`,
sender: 'BOT',
timestamp: '2026-06-11 01:02',
content: '안녕하세요, 구매 대행 봇입니다.',
editorScript: [
{
type: 'paragraph',
children: [
{ text: `${partnerName} 조달담당자님 안녕하십니까.\n` },
{ text: `이번에 진행되는 ${targetProduct?.name} 품목에 대해 당사 타깃가는 ` },
{ text: `${targetNegoPrice.toLocaleString('ko-KR')}원`, bold: true, color: 'primary' },
{ text: ' 수준입니다. 상호 이익 극대화를 위해 적합 단가를 제안해주시면 검토 후 즉시 타결 또는 와일드카드 혜택이 적용됩니다.' },
],
},
],
},
{
id: `msg-${estId}-part`,
sender: 'PARTNER',
timestamp: '2026-06-11 01:05',
content: `안녕하세요. 본 제품은 제조 원가 고사양으로 인해 타사 대비 높은 정밀도가 들어갑니다. 우선 1차 투찰로 ${initialPartnerBid.toLocaleString()}원을 입력 제출합니다.`,
},
],
};
}
@@ -0,0 +1,236 @@
import type { ItemResponse } from '@/api/generated/model/itemResponse';
import type { SupplierResponse } from '@/api/generated/model/supplierResponse';
import type { QuotationSettingResponse } from '@/api/generated/model/quotationSettingResponse';
import type { QuotationResponse } from '@/api/generated/model/quotationResponse';
import type {
Product,
Partner,
QuotationSetting,
Estimate,
ChatSession,
NegotiationCard,
} from '@/types';
export type { Product, Partner, QuotationSetting, Estimate, ChatSession, NegotiationCard } from '@/types';
// ── 서버 응답 → UI 모델 매퍼 ─────────────────────────────────────────────
// BaseRestApiResponse 봉투에서 내부 payload만 꺼낸다.
export function unwrap<T>(env: unknown): T | undefined {
return (env as { data?: { data?: T | null } } | undefined)?.data?.data ?? undefined;
}
export function mapItem(it: ItemResponse): Product {
return { ...it, id: it.item_id, minPrice: Math.round((it.price || 0) * 0.83), status: 'ACTIVE' };
}
export function mapSupplier(sp: SupplierResponse): Partner {
return {
supplier_id: sp.supplier_id,
company_id: sp.company_id,
name: sp.name,
code: sp.code ?? null,
manager_name: sp.manager_name ?? null,
manager_email: sp.manager_email ?? null,
priority: sp.priority ?? null,
created_at: sp.created_at,
updated_at: sp.updated_at,
id: sp.supplier_id,
managerName: sp.manager_name || '',
managerEmail: sp.manager_email || '',
managerPhone: sp.manager_contact_number || '',
rank: sp.priority === 'HIGH' ? 'S' : sp.priority === 'MEDIUM' ? 'A' : 'B',
status: 'ACTIVE',
};
}
export function mapSetting(s: QuotationSettingResponse): QuotationSetting {
return {
qt_setting_id: s.qt_setting_id,
user_id: s.user_id || '',
target_margin: String(s.target_margin_rate ?? ''),
anchoring_value: String(s.anchoring_value ?? ''),
card_use_count: String(s.card_count ?? ''),
created_at: s.created_at,
updated_at: s.updated_at,
deleted: false,
};
}
export function mapQuotation(q: QuotationResponse): Estimate {
return {
...(q as Partial<Estimate>),
id: q.qt_id,
title: q.name,
dueDate: q.end_time,
winnerPartnerId: q.preferred_sp_id ?? null,
isEqualPrice: !!q.equal_bid_yn,
partnerIds: [],
usedCardIds: [],
};
}
// ── 견적상태 정규화(영문 enum / 한글 DDL 혼용 대응) ──────────────────────
export type QtStatusKey = '견적생성' | '견적진행중' | '견적마감' | '협상보류';
export const QUOTATION_STATUS_FILTERS: QtStatusKey[] = [
'견적생성',
'견적진행중',
'견적마감',
'협상보류',
];
export function normalizeQuotationStatus(status?: string | null): QtStatusKey | '' {
switch (status) {
case 'PROCESSING':
case '견적생성':
return '견적생성';
case 'ACTIVE':
case '견적진행중':
return '견적진행중';
case 'COMPLETED':
case '견적마감':
return '견적마감';
case 'STOPPED':
case '협상보류':
return '협상보류';
default:
return '';
}
}
// ── 상세 드로어용 파생 뷰 모델(서버 미연동 영역의 목업 보강 포함) ────────
export type BidSummaryView = {
bid_summary_id: string;
status: string;
qt_iteration: number;
has_preferred: boolean;
preferred_sp_id: string | null;
preferred_sp_name: string;
equal_data: string;
};
export type SessionView = {
session_id: string;
qt_id: string;
supplier_id: string;
supplier_name: string;
item_id: string;
item_name: string;
status: string;
target_price: number;
bid_price: number | null;
bid_at: string;
reject_reason: string | null;
reject_price: number | null;
reject_delivery_type: string | null;
end_time: string;
};
export type QuotationCardView = {
session_card_id: string;
card_name: string;
type: string;
};
// 견적당 1개의 입찰 요약(bid_summary). est-1~3은 데모용 정적 매핑, 그 외는 견적 데이터에서 산출.
export function buildBidSummary(est: Estimate, partners: Partner[]): BidSummaryView {
if (est.id === 'est-1') {
return {
bid_summary_id: 'bid-summary-111-uuid',
status: '입찰진행중 (ACTIVE)',
qt_iteration: 2,
has_preferred: true,
preferred_sp_id: 'part-1',
preferred_sp_name: '(주)우성테크놀로지',
equal_data: '-',
};
}
if (est.id === 'est-2') {
return {
bid_summary_id: 'bid-summary-222-uuid',
status: '입찰종료 (COMPLETED)',
qt_iteration: 1,
has_preferred: true,
preferred_sp_id: 'part-2',
preferred_sp_name: '대현정밀공업 (주)',
equal_data: JSON.stringify({ 'part-2': 730000, 'part-3': 730000 }),
};
}
if (est.id === 'est-3') {
return {
bid_summary_id: 'bid-summary-333-uuid',
status: '입찰활성화 (ACTIVE)',
qt_iteration: 1,
has_preferred: false,
preferred_sp_id: null,
preferred_sp_name: '-',
equal_data: '-',
};
}
return {
bid_summary_id: `bid-summary-${est.id}`,
status: est.status === 'COMPLETED' ? '입찰종료 (COMPLETED)' : '입찰활성화 (ACTIVE)',
qt_iteration: 1,
has_preferred: !!est.winnerPartnerId,
preferred_sp_id: est.winnerPartnerId || null,
preferred_sp_name: est.winnerPartnerId
? partners.find((p) => p.id === est.winnerPartnerId)?.name || '-'
: '-',
equal_data: '-',
};
}
// 협력사별 1개의 세션(sessions). 채팅 세션 + 상품/협력사 정보를 합성.
export function buildSessions(
est: Estimate,
sessions: ChatSession[],
partners: Partner[],
products: Product[],
): SessionView[] {
return sessions.map((sess) => {
const supplierObj = partners.find((p) => p.id === sess.id);
const matchedProduct = products.find((p) => p.id === est.productId);
let reject_reason: string | null = null;
let reject_price: number | null = null;
let reject_delivery_type: string | null = null;
if (sess.id === 'part-2' && est.id === 'est-1') {
reject_reason = '셀 공급 마진 미달로 단가 수용 한계 봉착';
reject_price = 1480000;
reject_delivery_type = '특수 보온 수송 차량 필요';
}
return {
session_id: `sess-${est.id}-${sess.id}`,
qt_id: est.id ?? '',
supplier_id: sess.id,
supplier_name: supplierObj?.name || sess.partnerName,
item_id: est.productId || 'prod-1',
item_name: matchedProduct?.name || '부품',
status: sess.status || '협상중',
target_price: Math.round((matchedProduct?.price || 1000000) * 0.9),
bid_price: sess.currentBid || null,
bid_at: sess.bidTime || '2026-06-11 09:00',
reject_reason,
reject_price,
reject_delivery_type,
end_time: est.end_time || est.dueDate || '미지정',
};
});
}
// 견적에 매핑된 협상카드(quotation_cards N:M).
export function buildQuotationCards(est: Estimate, cards: NegotiationCard[]): QuotationCardView[] {
return (est.usedCardIds ?? []).map((cId) => {
const matchedCard = cards.find((c) => c.id === cId);
return {
session_card_id: `scard-${est.id}-${cId}`,
card_name: matchedCard?.title || '-',
type: matchedCard?.isWildcard ? '와일드 카드' : '협상 카드',
};
});
}