[feat] negodata/front: 상품·협력사 목록 서버 페이지네이션·검색 연동(재사용 useServerList) + 카드·견적 UI

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 4.8 committed 2026-06-18 11:03:11 +09:00
1 parent 7c244bca27
commit dd03c2aecd
28 files changed
+1104 -554

No files matched your search

@@ -3,6 +3,7 @@ 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import type { Product, Partner, QuotationSetting, NegotiationCard } from '../types';
import type { CreateQuotationInput } from '../hooks/useQuotations';
@@ -102,15 +103,20 @@ export function CreateQuotationWizard({
<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"
<Select
value={type}
onChange={(e) => setType(e.target.value as 'RE_NEGOTIATION' | 'RE_ESTIMATE')}
onValueChange={(v) => setType(v as 'RE_NEGOTIATION' | 'RE_ESTIMATE')}
>
<option value="RE_NEGOTIATION">재협상</option>
<option value="RE_ESTIMATE">재견적</option>
</select>
<SelectTrigger id="wizard-type" className="w-full">
<SelectValue>
{(value) => (value === 'RE_ESTIMATE' ? '재견적' : '재협상')}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="RE_NEGOTIATION">재협상</SelectItem>
<SelectItem value="RE_ESTIMATE">재견적</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
@@ -127,19 +133,25 @@ export function CreateQuotationWizard({
<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>
<Select value={productId} onValueChange={setProductId}>
<SelectTrigger id="wizard-product" className="w-full">
<SelectValue>
{(value) => {
const p = products.find((pp) => pp.id === value);
return p
? `${p.name} [${p.code}] (기준가: ₩${(p.price ?? 0).toLocaleString()})`
: '협상 대상 상품을 고르세요...';
}}
</SelectValue>
</SelectTrigger>
<SelectContent>
{products.filter((p) => p.status === 'ACTIVE').map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name} [{p.code}] (기준가: ₩{(p.price ?? 0).toLocaleString()})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
)}
@@ -185,18 +197,25 @@ export function CreateQuotationWizard({
<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>
<Select value={settingId} onValueChange={setSettingId}>
<SelectTrigger id="wizard-setting-select" className="w-full">
<SelectValue>
{(value) => {
const qs = quotationSettings.find((s) => s.qt_setting_id === value);
return qs
? `[목표 마진: ${qs.target_margin}] ${qs.anchoring_value} (${qs.card_use_count})`
: '';
}}
</SelectValue>
</SelectTrigger>
<SelectContent>
{quotationSettings.map((qs) => (
<SelectItem key={qs.qt_setting_id} value={qs.qt_setting_id}>
[목표 마진: {qs.target_margin}] {qs.anchoring_value} ({qs.card_use_count})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
@@ -6,22 +6,25 @@ import {
MessageSquare,
Layers,
Info,
Sparkles,
} 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 {
useGetQuotationSessions,
useGetSessionChat,
useGetQuotationCards,
} from '@/api/generated/quotation/quotation';
import {
type Estimate,
type Product,
type Partner,
type QuotationSetting,
type ChatSession,
type NegotiationCard,
normalizeQuotationStatus,
buildBidSummary,
buildSessions,
buildQuotationCards,
mapServerSessionView,
mapServerCardView,
} from '../types';
type DrawerTab = 'status' | 'cards' | 'chat';
@@ -30,9 +33,7 @@ type QuotationDetailDrawerProps = {
estimate: Estimate;
products: Product[];
partners: Partner[];
cards: NegotiationCard[];
quotationSettings: QuotationSetting[];
sessions: ChatSession[];
onStop: (id: string, name: string) => void;
onClose: () => void;
};
@@ -41,25 +42,36 @@ 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 qtId = estimate.id ?? '';
// 협상 세션·사용 카드는 견적 단위, 채팅은 선택 세션 단위로 서버에서 읽는다.
const sessionsQuery = useGetQuotationSessions(qtId, { query: { enabled: !!qtId } });
const cardsQuery = useGetQuotationCards(qtId, { query: { enabled: !!qtId } });
const serverSessions = sessionsQuery.data?.sessions ?? [];
const serverCards = cardsQuery.data?.cards ?? [];
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null);
const effectiveSessionId = selectedSessionId ?? serverSessions[0]?.session_id ?? null;
const chatQuery = useGetSessionChat(effectiveSessionId ?? '', {
query: { enabled: !!effectiveSessionId },
});
const chatMessages = chatQuery.data?.messages ?? [];
const currentSession = serverSessions.find((s) => s.session_id === effectiveSessionId);
const currentSupplierName =
partners.find((p) => p.id === currentSession?.supplier_id)?.name || currentSession?.supplier_id || '-';
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);
const sessionViews = serverSessions.map((sd) => mapServerSessionView(sd, partners, products));
const quotationCardViews = serverCards.map(mapServerCardView);
// Quotations DDL 표시값
const q_name = estimate.name || estimate.title || '미지정';
@@ -73,8 +85,8 @@ export function QuotationDetailDrawer({
const q_memo = estimate.memo || '안내사항 없음';
const statusKey = normalizeQuotationStatus(q_status);
const goToChat = (partnerId: string) => {
setSelectedChatPartnerId(partnerId);
const goToChat = (sessionId: string) => {
setSelectedSessionId(sessionId);
setActiveTab('chat');
};
@@ -107,7 +119,7 @@ export function QuotationDetailDrawer({
>
<span>{showHeaderCards ? '데이터베이스 매핑 정보 접기 ▲' : '데이터베이스 매핑 정보 펼치기 ▼'}</span>
</button>
{estimate.status === 'ACTIVE' && (
{statusKey === '견적진행중' && (
<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"
@@ -287,8 +299,8 @@ export function QuotationDetailDrawer({
key={tab.id}
onClick={() => {
setActiveTab(tab.id);
if (tab.id === 'chat' && sessions.length > 0 && !selectedChatPartnerId) {
setSelectedChatPartnerId(sessions[0].id);
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 ${
@@ -329,6 +341,13 @@ export function QuotationDetailDrawer({
</TableRow>
</TableHeader>
<TableBody className="divide-y divide-border">
{sessionViews.length === 0 && (
<TableRow>
<TableCell colSpan={11} className="p-12 text-center text-muted-foreground">
참여 중인 협상 세션이 없습니다. (리스트가 비어 있습니다)
</TableCell>
</TableRow>
)}
{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>
@@ -336,7 +355,7 @@ export function QuotationDetailDrawer({
<div className="flex items-center gap-2">
<span>{sess.supplier_name}</span>
<button
onClick={() => goToChat(sess.supplier_id)}
onClick={() => goToChat(sess.session_id)}
title="협상 대화방으로 이동"
className="p-1 hover:bg-primary/10 rounded text-primary hover:text-primary/80 transition-colors cursor-pointer"
>
@@ -416,7 +435,7 @@ export function QuotationDetailDrawer({
) : (
<TableRow>
<TableCell colSpan={3} className="p-12 text-center text-muted-foreground">
해당 견적에 사용할 수 있는 카드가 매핑되지 않습니다.
사용된 협상 카드가 없습니다. (리스트가 비어 있습니다)
</TableCell>
</TableRow>
)}
@@ -430,38 +449,47 @@ export function QuotationDetailDrawer({
{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="w-1/3 border-r border-border bg-muted/20 flex flex-col">
<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;
{serverSessions.length === 0 && (
<div className="p-4 text-center text-muted-foreground text-xs font-mono">
참여 협상 세션이 없습니다. (리스트가 비어 있습니다)
</div>
)}
{serverSessions.map((sd) => {
const isSelected = sd.session_id === effectiveSessionId;
const name = partners.find((p) => p.id === sd.supplier_id)?.name || sd.supplier_id;
const statusLabel = sd.status === 2 ? '협상종료' : sd.status === 3 ? '협상거부' : '협상중';
return (
<button
key={sess.id}
onClick={() => setSelectedChatPartnerId(sess.id)}
key={sd.session_id}
onClick={() => setSelectedSessionId(sd.session_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="font-bold text-foreground text-xs">{name}</span>
<span
className={`text-[9px] font-bold px-1.5 py-0.5 rounded ${
sess.status === 'REJECTED' || sess.status === '협상거부'
statusLabel === '협상거부'
? 'bg-rose-100 text-rose-800 dark:bg-rose-950/30 dark:text-rose-300'
: sess.status === 'COMPLETED' || sess.status === '협상종료'
: statusLabel === '협상종료'
? '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}
{statusLabel}
</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>
<span className="font-bold text-foreground">
{sd.bid_price ? `₩${Number(sd.bid_price).toLocaleString()}` : '-'}
</span>
</div>
</button>
);
@@ -473,32 +501,31 @@ export function QuotationDetailDrawer({
<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>
채널: <strong className="text-foreground">{currentSupplierName}</strong>
</div>
<div className="text-xs text-muted-foreground">
기록: <span className="font-semibold text-foreground">{currentChatSession?.messages.length}</span> 세션전화
기록: <span className="font-semibold text-foreground">{chatMessages.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>
);
}
{!effectiveSessionId ? (
<div className="h-full flex items-center justify-center text-muted-foreground font-mono text-xs">
선택된 대화 채널이 없습니다.
</div>
) : chatMessages.length === 0 ? (
<div className="h-full flex items-center justify-center text-muted-foreground font-mono text-xs">
기록된 협상 대화가 없습니다.
</div>
) : (
chatMessages.map((m) => {
const isBot = m.sender === 1;
const cardName = m.card_used_yn
? serverCards.find((c) => c.session_card_id === m.chat_id)?.name
: null;
return (
<div
key={msg.id}
key={m.chat_id}
className={`flex items-start gap-2.5 max-w-[85%] ${isBot ? 'mr-auto' : 'ml-auto flex-row-reverse'}`}
>
<div
@@ -511,9 +538,9 @@ export function QuotationDetailDrawer({
<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>{isBot ? 'Negosium AI Bot' : currentSupplierName}</span>
<span>·</span>
<span>{msg.timestamp}</span>
<span>#{m.index}</span>
</div>
<div
@@ -521,27 +548,21 @@ export function QuotationDetailDrawer({
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 className="font-bold">제시 단가 ₩{Number(m.target_price).toLocaleString()}</div>
{cardName && (
<div
className={`mt-1.5 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold ${
isBot ? 'bg-amber-100 text-amber-800 dark:bg-amber-950/30 dark:text-amber-300' : 'bg-white/20'
}`}
>
<Sparkles size={10} /> 협상카드: {cardName}
</div>
)}
</div>
</div>
</div>
);
})
) : (
<div className="h-full flex items-center justify-center text-muted-foreground font-mono text-xs">
선택된 대화 채널 데이터가 기록되지 않았습니다.
</div>
)}
</div>
@@ -61,12 +61,19 @@ export function QuotationSettingsModal({
<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">카드 사용 횟수</TableHead>
<TableHead className="p-2 text-center w-12">삭제</TableHead>
</TableRow>
</TableHeader>
<TableBody className="divide-y divide-border bg-background">
{settings.length === 0 && (
<TableRow>
<TableCell colSpan={4} className="p-6 text-center text-muted-foreground">
등록된 견적 세팅이 없습니다. (리스트가 비어 있습니다)
</TableCell>
</TableRow>
)}
{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>
@@ -95,15 +102,15 @@ export function QuotationSettingsModal({
<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%" />
<Input type="number" step="0.1" 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="예: 최초 즉각 앵커링" />
<Typography as="label" variant="muted" className="text-[10px] font-semibold">앵커링 값</Typography>
<Input type="number" step="0.01" value={anchoringValue} onChange={(e) => setAnchoringValue(e.target.value)} placeholder="예: 0.01" />
</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회 제한" />
<Input type="number" step="1" value={cardUseCount} onChange={(e) => setCardUseCount(e.target.value)} placeholder="예: 3" />
</div>
</div>
@@ -118,7 +118,7 @@ export function QuotationTable({ data, products, onOpenDetail, onStop }: Quotati
<span>상세 정보</span>
</button>
{est.status === 'ACTIVE' && (
{normalizeQuotationStatus(est.status) === '견적진행중' && (
<button
onClick={(e) => {
e.stopPropagation();
@@ -1,14 +1,23 @@
import { useEffect, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useListItems } from '@/api/generated/item/item';
import { useListSuppliers } from '@/api/generated/supplier/supplier';
import { useListSettings } from '@/api/generated/quotation-setting/quotation-setting';
import { useListCards } from '@/api/generated/card/card';
import { mapCardData } from '@/features/cards/types';
import {
useListSettings,
useCreateSetting,
useDeleteSetting,
getListSettingsQueryKey,
} from '@/api/generated/quotation-setting/quotation-setting';
import { useListQuotations } from '@/api/generated/quotation/quotation';
import type { ItemData } from '@/api/generated/model/itemData';
import type { SupplierData } from '@/api/generated/model/supplierData';
import type { QuotationSettingData } from '@/api/generated/model/quotationSettingData';
import type { QuotationData } from '@/api/generated/model/quotationData';
import type { CardData } from '@/api/generated/model/cardData';
import { showToast } from '@/lib/notify';
import type { Estimate, QuotationSetting, ChatSession, NegotiationCard, Product } from '@/types';
import type { Estimate, ChatSession, Product } from '@/types';
import { unwrap, mapItem, mapSupplier, mapSetting, mapQuotation } from '../types';
export type CreateQuotationInput = {
@@ -31,19 +40,22 @@ export type SettingInput = {
// 상품/협력사/세팅/견적은 서버(orval)에서 읽고, 견적·세팅·채팅은 로컬 state로 낙관적 갱신한다.
// (협상카드 카탈로그/채팅은 백엔드 미연동 → 빈 상태)
export function useQuotations() {
const queryClient = useQueryClient();
const itemsQuery = useListItems({ size: 100 });
const suppliersQuery = useListSuppliers({ size: 100 });
const cardsQuery = useListCards({ size: 100 });
const settingsQuery = useListSettings();
const quotationsQuery = useListQuotations(undefined);
const createSettingMutation = useCreateSetting();
const deleteSettingMutation = useDeleteSetting();
const products = (unwrap<{ items?: ItemData[] }>(itemsQuery.data)?.items ?? []).map(mapItem);
const partners = (unwrap<{ suppliers?: SupplierData[] }>(suppliersQuery.data)?.suppliers ?? []).map(mapSupplier);
const [quotationSettings, setQuotationSettings] = useState<QuotationSetting[]>([]);
useEffect(() => {
const s = unwrap<{ settings?: QuotationSettingData[] }>(settingsQuery.data)?.settings;
if (s) setQuotationSettings(s.map(mapSetting));
}, [settingsQuery.data]);
// 견적 세팅은 서버가 정본 — 목록 쿼리에서 바로 파생하고, 추가/삭제 후 쿼리를 무효화해 재조회한다.
const quotationSettings = (
unwrap<{ settings?: QuotationSettingData[] }>(settingsQuery.data)?.settings ?? []
).map(mapSetting);
const [quotations, setQuotations] = useState<Estimate[]>([]);
useEffect(() => {
@@ -51,30 +63,10 @@ export function useQuotations() {
if (qs) setQuotations(qs.map(mapQuotation));
}, [quotationsQuery.data]);
// 협상카드 카탈로그/채팅은 아직 백엔드 미연동 → 빈 상태.
const [cards] = useState<NegotiationCard[]>([]);
// 협상카드 카탈로그는 서버(orval)에서 읽어 단계 3/3 카드 선택지로 쓴다. 채팅은 아직 미연동.
const cards = (unwrap<{ cards?: CardData[] }>(cardsQuery.data)?.cards ?? []).map(mapCardData);
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;
@@ -82,36 +74,49 @@ export function useQuotations() {
showToast("해당 협상이 관리자에 의하여 '협상보류' 상태로 지정되었습니다.", 'info');
};
// 견적 세팅 추가. 검증 실패 시 toast 후 false.
const invalidateSettings = () =>
queryClient.invalidateQueries({ queryKey: getListSettingsQueryKey() });
// 견적 세팅 추가 — 서버 등록. 입력은 목표 마진율(%) / 앵커링 값 / 카드 사용 횟수(정수).
// 백엔드는 target_margin_rate 를 비율(0.12)로 저장하므로 % 입력을 100 으로 나눠 보낸다.
const addSetting = (input: SettingInput): boolean => {
if (!input.targetMargin.trim() || !input.anchoringValue.trim() || !input.cardUseCount.trim()) {
showToast('모든 세팅 항목을 입력해야 합니다.', 'error');
const marginPct = Number(String(input.targetMargin).replace('%', '').trim());
const anchoring = Number(String(input.anchoringValue).trim());
const cardCount = parseInt(String(input.cardUseCount).replace(/[^0-9-]/g, ''), 10);
if (!Number.isFinite(marginPct) || !Number.isFinite(anchoring) || !Number.isInteger(cardCount)) {
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');
createSettingMutation.mutate(
{ data: { target_margin_rate: marginPct / 100, anchoring_value: anchoring, card_count: cardCount } },
{
onSuccess: () => {
invalidateSettings();
showToast('새 견적 세팅이 등록되었습니다.', 'success');
},
onError: () => showToast('견적 세팅 등록에 실패했습니다.', 'error'),
},
);
return true;
};
// 견적 세팅 삭제(최소 1개 유지).
// 견적 세팅 삭제(서버 soft-delete, 최소 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');
deleteSettingMutation.mutate(
{ qtSettingId: id },
{
onSuccess: () => {
invalidateSettings();
showToast('세팅이 삭제되었습니다.', 'info');
},
onError: () => showToast('세팅 삭제에 실패했습니다.', 'error'),
},
);
};
// 신규 견적 발의 — 견적 레코드 + 협력사별 채팅 세션을 생성. 검증 실패 시 toast 후 false.
@@ -157,7 +162,7 @@ export function useQuotations() {
setChatSessions((prev) => ({ ...prev, [estId]: generatedSessions }));
setQuotations((prev) => [newQuotationRecord, ...prev]);
showToast(`신규 견정 제안서[${input.title}]가 발행되었습니다. 협상 세션 수립 중... (폴링 가동)`, 'info');
showToast(`신규 견적 제안서[${input.title}]가 발행되었습니다.`, 'info');
return true;
};
@@ -2,6 +2,8 @@ import type { ItemData } from '@/api/generated/model/itemData';
import type { SupplierData } from '@/api/generated/model/supplierData';
import type { QuotationSettingData } from '@/api/generated/model/quotationSettingData';
import type { QuotationData } from '@/api/generated/model/quotationData';
import type { SessionData } from '@/api/generated/model/sessionData';
import type { QuotationCardData } from '@/api/generated/model/quotationCardData';
import type {
Product,
Partner,
@@ -45,12 +47,14 @@ export function mapSupplier(sp: SupplierData): Partner {
}
export function mapSetting(s: QuotationSettingData): QuotationSetting {
// 서버는 target_margin_rate 를 비율(0.12)로 저장 → UI 는 퍼센트(12%)로 표기.
const ratePct = Number(s.target_margin_rate ?? 0) * 100;
return {
qt_setting_id: s.qt_setting_id,
user_id: s.user_id || '',
target_margin: String(s.target_margin_rate ?? ''),
target_margin: `${Number.isFinite(ratePct) ? +ratePct.toFixed(2) : 0}%`,
anchoring_value: String(s.anchoring_value ?? ''),
card_use_count: String(s.card_count ?? ''),
card_use_count: `${s.card_count ?? 0}회`,
created_at: s.created_at ?? '',
updated_at: s.updated_at ?? '',
deleted: false,
@@ -62,14 +66,27 @@ export function mapQuotation(q: QuotationData): Estimate {
...(q as unknown as Partial<Estimate>),
id: q.qt_id,
title: q.name,
dueDate: q.end_time,
winnerPartnerId: q.preferred_sp_id ?? null,
type: normalizeQuotationType(q.type),
status: normalizeQuotationStatus(q.status) || String(q.status ?? ''),
settingApplied: q.qt_setting_id, // 드로어 견적세팅 카드가 qt_setting_id 로 매칭
dueDate: formatDueDate(q.end_time),
participationCount: 0,
winnerPartnerId: q.preferred_sp_id ?? q.preferred_sp_name ?? null,
isEqualPrice: !!q.equal_bid_yn,
partnerIds: [],
usedCardIds: [],
};
}
// 서버 end_time(ISO) → 'YYYY-MM-DD HH:mm' 표기. 파싱 실패 시 원본 유지.
function formatDueDate(end?: string | null): string {
if (!end) return '미지정';
const d = new Date(end);
if (Number.isNaN(d.getTime())) return end;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
// ── 견적상태 정규화(영문 enum / 한글 DDL 혼용 대응) ──────────────────────
export type QtStatusKey = '견적생성' | '견적진행중' | '견적마감' | '협상보류';
@@ -81,17 +98,22 @@ export const QUOTATION_STATUS_FILTERS: QtStatusKey[] = [
'협상보류',
];
export function normalizeQuotationStatus(status?: string | null): QtStatusKey | '' {
// QuotationStatus 코드(SMALLINT) ↔ 한글 상태키. 영문 enum/한글 DDL/숫자 코드 혼용을 모두 흡수.
export function normalizeQuotationStatus(status?: string | number | null): QtStatusKey | '' {
switch (status) {
case 1:
case 'PROCESSING':
case '견적생성':
return '견적생성';
case 2:
case 'ACTIVE':
case '견적진행중':
return '견적진행중';
case 3:
case 'COMPLETED':
case '견적마감':
return '견적마감';
case 4:
case 'STOPPED':
case '협상보류':
return '협상보류';
@@ -100,6 +122,13 @@ export function normalizeQuotationStatus(status?: string | null): QtStatusKey |
}
}
// QuotationType 코드(1=재협상, 2=재견적) ↔ UI 유형값. 이미 문자열이면 그대로 통과.
export function normalizeQuotationType(type?: string | number | null): 'RE_NEGOTIATION' | 'RE_ESTIMATE' {
if (type === 1 || type === 'RE_NEGOTIATION') return 'RE_NEGOTIATION';
if (type === 2 || type === 'RE_ESTIMATE') return 'RE_ESTIMATE';
return type === '재협상' ? 'RE_NEGOTIATION' : 'RE_ESTIMATE';
}
// ── 상세 드로어용 파생 뷰 모델(서버 미연동 영역의 목업 보강 포함) ────────
export type BidSummaryView = {
@@ -223,6 +252,54 @@ export function buildSessions(
});
}
// ── 서버 연동 매퍼(negotiation.sessions / chats / 사용 카드) ──────────────
const SESSION_STATUS_LABEL: Record<number, string> = { 1: '협상중', 2: '협상종료', 3: '협상거부' };
const DELIVERY_TYPE_LABEL: Record<number, string> = { 1: '협력사배송', 2: '지정택배배송', 3: '픽업배송' };
// ISO 문자열 → 'YYYY-MM-DD HH:mm'. 빈 값/파싱 실패는 '-'.
export function fmtDateTime(s?: string | null): string {
if (!s) return '-';
const d = new Date(s);
if (Number.isNaN(d.getTime())) return s;
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
}
// 서버 SessionData → 협상현황 테이블 뷰. 협력사명/상품명은 이미 로드된 목록에서 해석.
// (SessionData 필드는 생성 타입 그대로 사용 — number|null / string|null, 캐스팅 없음.)
export function mapServerSessionView(sd: SessionData, partners: Partner[], products: Product[]): SessionView {
const supplier = partners.find((p) => p.id === sd.supplier_id);
const product = products.find((p) => p.id === sd.item_id);
return {
session_id: sd.session_id,
qt_id: sd.qt_id,
supplier_id: sd.supplier_id,
supplier_name: supplier?.name || sd.supplier_id,
item_id: sd.item_id,
item_name: product?.name || '부품',
status: SESSION_STATUS_LABEL[sd.status] || String(sd.status),
target_price: sd.target_price ?? 0,
bid_price: sd.bid_price ?? null,
bid_at: sd.bid_at ? fmtDateTime(sd.bid_at) : '-',
reject_reason: sd.reject_reason ?? null,
reject_price: sd.reject_price ?? null,
reject_delivery_type: sd.reject_delivery_type
? DELIVERY_TYPE_LABEL[sd.reject_delivery_type] || String(sd.reject_delivery_type)
: null,
end_time: fmtDateTime(sd.end_time),
};
}
// 서버 QuotationCardData → 사용 카드 뷰. type 2=와일드, 그 외 협상카드.
export function mapServerCardView(c: QuotationCardData): QuotationCardView {
return {
session_card_id: c.session_card_id,
card_name: c.name || '-',
type: c.type === 2 ? '와일드 카드' : '협상 카드',
};
}
// 견적에 매핑된 협상카드(quotation_cards N:M).
export function buildQuotationCards(est: Estimate, cards: NegotiationCard[]): QuotationCardView[] {
return (est.usedCardIds ?? []).map((cId) => {