[feat] negodata: 견적목록 상품조인 + 견적/카드 페이지네이션 + 견적중단 서버연동 + 발의→등록

- 견적 목록에 대표 상품(세션 item) 조인 노출 → '대상 상품 확인 불가' 해소
  (backend protocol/crud/service + orval 재생성 + front mapQuotation 매핑)
- 견적·협상카드 목록 클라이언트 페이지네이션 추가 (useClientPagination)
- 견적중단을 서버 stop_quotation 호출로 영속 처리(상태=견적마감)
- 신규 협상견적 라벨 발의→등록 통일
- 발의 위저드 카드선택에 협상/와일드 구분 뱃지 추가

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 17:46:18 +09:00
1 parent 53b8a78de7
commit 4f0e4c29ce
25 files changed
+668 -165

No files matched your search

@@ -1,18 +1,21 @@
import type { ReactNode } from 'react';
import { DataTable } from '@/components/ui/data-table';
import type { NegotiationCard } from '../types';
type CardTableProps = {
data: NegotiationCard[];
onEdit: (card: NegotiationCard) => void;
footer?: ReactNode;
};
export function CardTable({ data, onEdit }: CardTableProps) {
export function CardTable({ data, onEdit, footer }: CardTableProps) {
return (
<DataTable
data={data}
rowKey={(card) => card.id}
onRowClick={onEdit}
empty="데이터가 없습니다."
footer={footer}
columns={[
{
header: '구분',
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { X, PlusSquare, ArrowRight } from 'lucide-react';
import { X, PlusSquare, ArrowRight, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Typography } from '@/components/ui/typography';
import { Input } from '@/components/ui/input';
@@ -13,7 +13,7 @@ type CreateQuotationWizardProps = {
partners: Partner[];
cards: NegotiationCard[];
quotationSettings: QuotationSetting[];
onCreate: (input: CreateQuotationInput) => boolean;
onCreate: (input: CreateQuotationInput) => boolean | Promise<boolean>;
onClose: () => void;
};
@@ -34,6 +34,7 @@ export function CreateQuotationWizard({
const [dueDate, setDueDate] = useState('2026-06-15T18:00');
const [settingId, setSettingId] = useState(quotationSettings[0]?.qt_setting_id ?? '');
const [selectedCardIds, setSelectedCardIds] = useState<string[]>([]);
const [submitting, setSubmitting] = useState(false);
if (!open) return null;
@@ -46,28 +47,44 @@ export function CreateQuotationWizard({
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();
const handleSubmit = async () => {
if (submitting) return;
setSubmitting(true);
try {
// 서버가 견적+세션 생성을 끝내고 응답할 때까지 기다린 뒤에 완료(닫기) 처리한다.
const ok = await onCreate({
title,
type,
productId,
partnerIds: selectedPartnerIds,
dueDate,
settingId,
cardIds: selectedCardIds,
});
if (ok) onClose();
} finally {
setSubmitting(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs">
{submitting && (
<div className="fixed inset-0 z-[60] flex items-center justify-center">
<div className="flex flex-col items-center gap-3 rounded-xl bg-card px-8 py-6 shadow-2xl border border-border">
<Loader2 className="text-primary animate-spin" size={44} strokeWidth={2.5} />
<span className="text-sm font-semibold text-foreground font-mono">협상견적 생성 중…</span>
<span className="text-[11px] text-muted-foreground font-mono">견적 · 협상 세션 등록 중</span>
</div>
</div>
)}
<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>
<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} />
@@ -233,7 +250,16 @@ export function CreateQuotationWizard({
>
<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>
<div className="flex items-center gap-1.5">
<span className="text-[10px] text-muted-foreground font-mono block leading-none">{card.code}</span>
<span
className={`text-[9px] font-mono px-1.5 py-0.5 rounded leading-none ${
card.isWildcard ? 'bg-amber-50 text-amber-700' : 'bg-zinc-100 text-zinc-600'
}`}
>
{card.isWildcard ? '와일드' : '협상'}
</span>
</div>
<span className="text-xs text-foreground mt-1 block leading-tight">{card.title}</span>
</div>
</div>
@@ -263,8 +289,8 @@ export function CreateQuotationWizard({
다음 단계로
</Button>
) : (
<Button type="button" size="sm" onClick={handleSubmit}>
견적 발의 등록
<Button type="button" size="sm" onClick={handleSubmit} disabled={submitting}>
{submitting ? '생성 중…' : '협상견적 등록'}
</Button>
)}
</div>
@@ -8,7 +8,10 @@ import {
Layers,
Sparkles,
Package,
ExternalLink,
Copy,
} from 'lucide-react';
import { showToast } from '@/lib/notify';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Typography } from '@/components/ui/typography';
import { Input } from '@/components/ui/input';
@@ -390,6 +393,7 @@ export function QuotationDetailDrawer({
<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">협상 URL</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>
@@ -404,7 +408,7 @@ export function QuotationDetailDrawer({
<TableBody className="divide-y divide-border">
{sessionViews.length === 0 && (
<TableRow>
<TableCell colSpan={11} className="p-12 text-center text-muted-foreground">
<TableCell colSpan={12} className="p-12 text-center text-muted-foreground">
참여 중인 협상 세션이 없습니다. (리스트가 비어 있습니다)
</TableCell>
</TableRow>
@@ -424,6 +428,33 @@ export function QuotationDetailDrawer({
</button>
</div>
</TableCell>
<TableCell className="p-3 font-mono">
{sess.url ? (
<div className="flex items-center gap-1.5">
<a
href={sess.url}
target="_blank"
rel="noopener noreferrer"
title={sess.url}
className="inline-flex items-center gap-1 px-2 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20 transition-colors text-[10px] font-semibold"
>
<ExternalLink size={11} /> 세션 열기
</a>
<button
onClick={() => {
void navigator.clipboard?.writeText(sess.url);
showToast('협상 URL을 복사했습니다.', 'success');
}}
title="협상 URL 복사"
className="p-1 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
>
<Copy size={12} />
</button>
</div>
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell className="p-3 font-semibold font-sans">{sess.item_name}</TableCell>
<TableCell className="p-3 text-center">
<span
@@ -1,3 +1,4 @@
import type { ReactNode } from 'react';
import { Clock, Building2 } from 'lucide-react';
import { DataTable } from '@/components/ui/data-table';
import { type Estimate, type Product, normalizeQuotationStatus } from '../types';
@@ -6,6 +7,7 @@ type QuotationTableProps = {
data: Estimate[];
products: Product[];
onOpenDetail: (id: string) => void;
footer?: ReactNode;
};
const statusBadgeClass = (status?: string | null) => {
@@ -23,18 +25,20 @@ const statusBadgeClass = (status?: string | null) => {
}
};
export function QuotationTable({ data, products, onOpenDetail }: QuotationTableProps) {
export function QuotationTable({ data, products, onOpenDetail, footer }: QuotationTableProps) {
return (
<DataTable
data={data}
rowKey={(est) => est.id ?? ''}
onRowClick={(est) => onOpenDetail(est.id ?? '')}
empty="진행 중인 전자 견적 및 자동 협상 계약 내역이 존재하지 않습니다."
footer={footer}
columns={[
{
header: '견적건명',
cell: (est) => {
const product = products.find((p) => p.id === est.productId);
const productName = product?.name ?? est.productName; // 목록에 없으면 서버 조인 상품명으로 폴백
return (
<div>
<span className="font-bold text-sm text-foreground hover:underline cursor-pointer block">
@@ -42,7 +46,7 @@ export function QuotationTable({ data, products, onOpenDetail }: QuotationTableP
</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()})
대상 상품: {productName ?? '확인 불가'} (₩{(product?.price ?? 0).toLocaleString()})
</span>
</div>
);
@@ -10,7 +10,13 @@ import {
useDeleteSetting,
getListSettingsQueryKey,
} from '@/api/generated/quotation-setting/quotation-setting';
import { useListQuotations } from '@/api/generated/quotation/quotation';
import {
useListQuotations,
useCreateQuotation,
useStopQuotation,
getListQuotationsQueryKey,
} from '@/api/generated/quotation/quotation';
import type { ReqCreateQuotation } from '@/api/generated/model/reqCreateQuotation';
import type { ItemData } from '@/api/generated/model/itemData';
import type { SupplierData } from '@/api/generated/model/supplierData';
import type { QuotationSettingData } from '@/api/generated/model/quotationSettingData';
@@ -18,7 +24,7 @@ import type { QuotationData } from '@/api/generated/model/quotationData';
import type { CardData } from '@/api/generated/model/cardData';
import { showToast } from '@/lib/notify';
import { confirm } from '@/lib/confirm';
import type { Estimate, ChatSession, Product } from '@/types';
import type { Estimate } from '@/types';
import { unwrap, mapItem, mapSupplier, mapSetting, mapQuotation } from '../types';
export type CreateQuotationInput = {
@@ -49,6 +55,11 @@ export function useQuotations() {
const quotationsQuery = useListQuotations(undefined);
const createSettingMutation = useCreateSetting();
const deleteSettingMutation = useDeleteSetting();
const createQuotationMutation = useCreateQuotation();
const stopQuotationMutation = useStopQuotation();
const invalidateQuotations = () =>
queryClient.invalidateQueries({ queryKey: getListQuotationsQueryKey(undefined) });
const products = (unwrap<{ items?: ItemData[] }>(itemsQuery.data)?.items ?? []).map(mapItem);
const partners = (unwrap<{ suppliers?: SupplierData[] }>(suppliersQuery.data)?.suppliers ?? []).map(mapSupplier);
@@ -64,15 +75,27 @@ export function useQuotations() {
if (qs) setQuotations(qs.map(mapQuotation));
}, [quotationsQuery.data]);
// 협상카드 카탈로그는 서버(orval)에서 읽어 단계 3/3 카드 선택지로 쓴다. 채팅은 아직 미연동.
// 협상카드 카탈로그는 서버(orval)에서 읽어 단계 3/3 카드 선택지로 쓴다.
const cards = (unwrap<{ cards?: CardData[] }>(cardsQuery.data)?.cards ?? []).map(mapCardData);
const [chatSessions, setChatSessions] = useState<Record<string, ChatSession[]>>({});
// 협상 강제중단 → '협상보류'.
// 협상 강제중단 → 서버 stop_quotation 호출(상태 '견적마감'으로 영속). 성공 시 목록 무효화로 서버값 재동기화.
const stopNegotiation = async (id: string, name: string) => {
if (!(await confirm({ title: '협상 강제중단', description: `현재 입찰 중인 [${name}] 단가 협상 절차를 즉시 조기 중단(강제종료)하시겠습니까?`, confirmText: '중단', destructive: true }))) return;
setQuotations((prev) => prev.map((e) => (e.id === id ? { ...e, status: '협상보류' } : e)));
showToast("해당 협상이 관리자에 의하여 '협상보류' 상태로 지정되었습니다.", 'info');
// 낙관적 갱신 — 서버가 CLOSED 로 바꾸므로 화면도 '견적마감'으로 선반영.
setQuotations((prev) => prev.map((e) => (e.id === id ? { ...e, status: '견적마감' } : e)));
stopQuotationMutation.mutate(
{ qtId: id },
{
onSuccess: () => {
invalidateQuotations();
showToast(`[${name}] 협상이 중단되어 '견적마감' 처리되었습니다.`, 'info');
},
onError: () => {
invalidateQuotations(); // 실패 시 서버 진짜값으로 롤백
showToast('견적 중단에 실패했습니다. 잠시 후 다시 시도해 주세요.', 'error');
},
},
);
};
const invalidateSettings = () =>
@@ -120,51 +143,48 @@ export function useQuotations() {
);
};
// 신규 견적 발의 — 견적 레코드 + 협력사별 채팅 세션을 생성. 검증 실패 시 toast 후 false.
const createQuotation = (input: CreateQuotationInput): boolean => {
// 신규 협상견적 등록 — 서버에 견적 + 협력사별 협상 세션(상품×공급사)을 생성한다.
// 서버 응답(실제 qt_id)을 기다린 뒤에야 완료 처리한다. 성공 시 새 qt_id 반환, 실패/검증오류 시 null.
const createQuotation = async (input: CreateQuotationInput): Promise<string | null> => {
if (!input.title.trim()) {
showToast('견적 건명을 올바르게 작성해 주세요.', 'error');
return false;
return null;
}
if (!input.productId) {
showToast('협상 대상 품목을 지정하지 않았습니다.', 'error');
return false;
return null;
}
if (input.partnerIds.length === 0) {
showToast('최소 한 곳 이상의 벤더사(참여 협력사)를 선정해 주세요.', 'error');
return false;
return null;
}
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 payload: ReqCreateQuotation = {
qt_setting_id: input.settingId,
name: input.title,
type: input.type === 'RE_ESTIMATE' ? 2 : 1,
end_time: new Date(input.dueDate).toISOString(),
item_ids: [input.productId],
supplier_ids: input.partnerIds,
card_ids: input.cardIds,
};
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;
try {
const res = await createQuotationMutation.mutateAsync({ data: payload });
const qtId = res?.quotation?.qt_id ?? null;
// 서버가 result.success=false 거나 qt_id 가 없으면 실패로 처리(HTTP 200 이어도). 모달은 그대로 유지.
if (!res?.result?.success || !qtId) {
showToast(`견적 생성 실패: ${res?.result?.desc ?? '서버 오류'}`, 'error');
return null;
}
// 목록 재조회가 끝나야 새 견적이 정본 목록에 들어온다(상세 자동오픈이 그 행을 찾을 수 있게).
await invalidateQuotations();
showToast(`협상견적[${input.title}] 생성 완료 — 협상 세션 ${res?.sessions?.length ?? 0}건.`, 'success');
return qtId;
} catch {
showToast('견적 생성에 실패했습니다. 입력값을 확인해 주세요.', 'error');
return null;
}
};
return {
@@ -173,62 +193,9 @@ export function useQuotations() {
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()}원을 입력 제출합니다.`,
},
],
};
}
@@ -69,6 +69,8 @@ export function mapQuotation(q: QuotationData): Estimate {
type: normalizeQuotationType(q.type),
status: normalizeQuotationStatus(q.status) || String(q.status ?? ''),
settingApplied: q.qt_setting_id, // 드로어 견적세팅 카드가 qt_setting_id 로 매칭
productId: q.item_id ?? undefined, // 서버 목록 조인(세션 대표 상품). products 목록과 id 매칭용
productName: q.item_name ?? undefined, // products 목록에 없을 때 표기 폴백
dueDate: formatDueDate(q.end_time),
participationCount: q.participation_count ?? 0,
winnerPartnerId: q.preferred_sp_id ?? q.preferred_sp_name ?? null,
@@ -156,6 +158,7 @@ export type SessionView = {
reject_price: number | null;
reject_delivery_type: string | null;
end_time: string;
url: string; // 세션 chat 실행 URL(공급사 협상 프론트)
};
export type QuotationCardView = {
@@ -249,6 +252,7 @@ export function buildSessions(
reject_price,
reject_delivery_type,
end_time: est.end_time || est.dueDate || '미지정',
url: '',
};
});
}
@@ -289,6 +293,7 @@ export function mapServerSessionView(sd: SessionData, partners: Partner[], produ
? DELIVERY_TYPE_LABEL[sd.reject_delivery_type] || String(sd.reject_delivery_type)
: null,
end_time: fmtDateTime(sd.end_time),
url: sd.url || '',
};
}