[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:
1 parent
a6731dcb07
commit
87524bf6e8
288 files changed
+26363
-1
No files matched your search
@@ -0,0 +1,82 @@
|
||||
import {setAccessToken} from '../../api/mutator/custom-fetch';
|
||||
import {
|
||||
login as loginRequest,
|
||||
refreshToken as refreshRequest,
|
||||
me as fetchMe,
|
||||
} from '../../api/generated/auth/auth';
|
||||
import type {ResMe} from '../../api/generated/model/resMe';
|
||||
import type {ErrorInfo} from '../../api/generated/model/errorInfo';
|
||||
import {useAuthStore, type AuthUser, type UserRole} from '../../stores/auth';
|
||||
|
||||
const ACCESS_KEY = 'negodata.accessToken';
|
||||
const REFRESH_KEY = 'negodata.refreshToken';
|
||||
|
||||
// 백엔드 공통 응답: { result: {success, code, desc}, ...payload }.
|
||||
// result.success 가 false 면 desc 로 throw (HTTP 4xx 는 customFetch 가 ApiError 로 던짐).
|
||||
function ensureOk<T extends {result?: ErrorInfo}>(res: T): T {
|
||||
const r = res.result;
|
||||
if (r && r.success === false) throw new Error(r.desc || String(r.code ?? '') || 'request failed');
|
||||
return res;
|
||||
}
|
||||
|
||||
function toAuthUser(me: ResMe): AuthUser {
|
||||
return {
|
||||
company: me.company?.name ?? '',
|
||||
name: me.name ?? me.id ?? '',
|
||||
loginId: me.id ?? '',
|
||||
email: me.email ?? '',
|
||||
contact: me.contact_number ?? '',
|
||||
role: (me.role as UserRole) ?? '일반',
|
||||
};
|
||||
}
|
||||
|
||||
async function restore(): Promise<void> {
|
||||
const access = localStorage.getItem(ACCESS_KEY);
|
||||
const refresh = localStorage.getItem(REFRESH_KEY);
|
||||
if (!access && !refresh) return;
|
||||
|
||||
if (access) setAccessToken(access);
|
||||
try {
|
||||
const me = ensureOk(await fetchMe());
|
||||
useAuthStore.getState().setUser(toAuthUser(me));
|
||||
} catch {
|
||||
try {
|
||||
if (!refresh) throw new Error('no refresh token');
|
||||
// refresh 토큰은 Authorization 헤더(Bearer)로 보낸다 → accessToken 슬롯에 잠시 실어 보냄.
|
||||
setAccessToken(refresh);
|
||||
const {access_token = ''} = ensureOk(await refreshRequest());
|
||||
localStorage.setItem(ACCESS_KEY, access_token);
|
||||
setAccessToken(access_token);
|
||||
const me = ensureOk(await fetchMe());
|
||||
useAuthStore.getState().setUser(toAuthUser(me));
|
||||
} catch {
|
||||
localStorage.removeItem(ACCESS_KEY);
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
setAccessToken(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let restorePromise: Promise<void> | null = null;
|
||||
export function initAuth(): Promise<void> {
|
||||
if (!restorePromise) restorePromise = restore();
|
||||
return restorePromise;
|
||||
}
|
||||
|
||||
export async function login(loginId: string, password: string): Promise<ResMe> {
|
||||
const tokens = ensureOk(await loginRequest({id: loginId, password}));
|
||||
localStorage.setItem(ACCESS_KEY, tokens.access_token ?? '');
|
||||
localStorage.setItem(REFRESH_KEY, tokens.refresh_token ?? '');
|
||||
setAccessToken(tokens.access_token ?? null);
|
||||
const me = ensureOk(await fetchMe());
|
||||
useAuthStore.getState().setUser(toAuthUser(me));
|
||||
return me;
|
||||
}
|
||||
|
||||
// 백엔드에 logout 엔드포인트가 없으므로 클라이언트 상태만 비운다.
|
||||
export async function logout(): Promise<void> {
|
||||
localStorage.removeItem(ACCESS_KEY);
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
setAccessToken(null);
|
||||
useAuthStore.getState().setUser(null);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import {useAuthStore} from '../../stores/auth';
|
||||
import {login, logout} from './service';
|
||||
|
||||
export function useAuth() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
return {
|
||||
user,
|
||||
isLoggedIn: user !== null,
|
||||
login,
|
||||
logout,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { X, Layers } from 'lucide-react';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { type NegotiationCard, type CardTab, generateCardCode } from '../types';
|
||||
import type { CardInput } from '../hooks/useCards';
|
||||
|
||||
const schema = z.object({
|
||||
isWildcard: z.boolean(),
|
||||
code: z.string().trim().min(1, '카드번호는 필수 기입 사항입니다.'),
|
||||
title: z.string().trim().min(1, '카드이름은 필수 기입 사항입니다.'),
|
||||
scriptPreview: z.string().trim().min(1, '스크립트를 작성해 주십시오.'),
|
||||
status: z.enum(['ACTIVE', 'INACTIVE']),
|
||||
triggerCondition: z.string(),
|
||||
memo: z.string(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
type CardFormModalProps = {
|
||||
open: boolean;
|
||||
mode: 'create' | 'edit';
|
||||
card: NegotiationCard | null; // edit 모드 초기값 출처
|
||||
activeTab: CardTab; // create 시 기본 카드 종류 결정
|
||||
onCreate: (input: CardInput) => void;
|
||||
onUpdate: (id: string, input: CardInput) => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
function buildDefaults(
|
||||
mode: 'create' | 'edit',
|
||||
card: NegotiationCard | null,
|
||||
activeTab: CardTab,
|
||||
): FormValues {
|
||||
if (mode === 'edit' && card) {
|
||||
return {
|
||||
isWildcard: card.isWildcard,
|
||||
code: card.code,
|
||||
title: card.title,
|
||||
scriptPreview: card.scriptPreview,
|
||||
status: card.status,
|
||||
triggerCondition: card.triggerCondition || '',
|
||||
memo: card.memo || '',
|
||||
};
|
||||
}
|
||||
const wild = activeTab === 'WILD';
|
||||
return {
|
||||
isWildcard: wild,
|
||||
code: generateCardCode(wild),
|
||||
title: '',
|
||||
scriptPreview: '',
|
||||
status: 'ACTIVE',
|
||||
triggerCondition: '',
|
||||
memo: '',
|
||||
};
|
||||
}
|
||||
|
||||
// 협상카드/와일드카드 등록·수정 모달. react-hook-form + zod로 검증.
|
||||
// 페이지는 key={mode + card?.id}로 리마운트시켜 초기값을 주입한다.
|
||||
export function CardFormModal({
|
||||
open,
|
||||
mode,
|
||||
card,
|
||||
activeTab,
|
||||
onCreate,
|
||||
onUpdate,
|
||||
onClose,
|
||||
}: CardFormModalProps) {
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors },
|
||||
} = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: buildDefaults(mode, card, activeTab),
|
||||
});
|
||||
|
||||
const isWildcard = watch('isWildcard');
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const onValid = (v: FormValues) => {
|
||||
const input: CardInput = {
|
||||
title: v.title,
|
||||
code: v.code,
|
||||
scriptPreview: v.scriptPreview,
|
||||
status: v.status,
|
||||
isWildcard: v.isWildcard,
|
||||
triggerCondition: v.triggerCondition,
|
||||
memo: v.memo,
|
||||
};
|
||||
if (mode === 'create') {
|
||||
onCreate(input);
|
||||
showToast(`${v.isWildcard ? '와일드카드' : '협상카드'}가 추가되었습니다.`, 'success');
|
||||
} else if (card) {
|
||||
onUpdate(card.id, input);
|
||||
showToast('정보가 수정되었습니다.', 'success');
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs p-4">
|
||||
<div className="w-full max-w-lg bg-card border border-border rounded-lg shadow-2xl p-6 overflow-y-auto max-h-[90vh] 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">
|
||||
<Layers className="text-foreground" size={16} />
|
||||
<Typography variant="h3" className="text-sm">
|
||||
{mode === 'create'
|
||||
? isWildcard
|
||||
? '신규 와일드카드 등록'
|
||||
: '신규 협상카드 등록'
|
||||
: isWildcard
|
||||
? '와일드카드 정보 수정'
|
||||
: '협상카드 정보 수정'}
|
||||
</Typography>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit(onValid)} className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
{/* Card Type Selection */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="small" className="font-semibold">카드 종류</Typography>
|
||||
<Controller
|
||||
control={control}
|
||||
name="isWildcard"
|
||||
render={({ field }) => (
|
||||
<select
|
||||
id="form-card-is-wildcard"
|
||||
value={field.value ? 'WILD' : 'CARD'}
|
||||
onChange={(e) => {
|
||||
const wild = e.target.value === 'WILD';
|
||||
field.onChange(wild);
|
||||
if (mode === 'create') {
|
||||
setValue('code', generateCardCode(wild));
|
||||
}
|
||||
}}
|
||||
className="w-full p-2 bg-background border border-border rounded text-[11px] cursor-pointer focus:outline-none"
|
||||
>
|
||||
<option value="CARD">일반 협상카드</option>
|
||||
<option value="WILD">와일드카드</option>
|
||||
</select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Code */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="small" className="font-semibold">카드번호</Typography>
|
||||
<Input
|
||||
id="form-card-code"
|
||||
type="text"
|
||||
{...register('code')}
|
||||
placeholder="CARD-XXX 또는 WILD-XXX"
|
||||
/>
|
||||
{errors.code && <p className="text-[10px] text-rose-500">{errors.code.message}</p>}
|
||||
</div>
|
||||
|
||||
{/* Status */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="small" className="font-semibold block mb-1">협상 적용 여부</Typography>
|
||||
{isWildcard ? (
|
||||
<Controller
|
||||
control={control}
|
||||
name="status"
|
||||
render={({ field }) => (
|
||||
<div className="flex items-center gap-3 p-2 bg-muted/30 border border-border rounded-md h-[34px]">
|
||||
<button
|
||||
id="form-card-status-switch"
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={field.value === 'ACTIVE'}
|
||||
onClick={() => field.onChange(field.value === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE')}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-all duration-200 focus:outline-none ${
|
||||
field.value === 'ACTIVE' ? 'bg-emerald-600 dark:bg-emerald-500' : 'bg-zinc-300 dark:bg-zinc-700'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`pointer-events-none block h-4 w-4 rounded-full bg-white shadow transition-all duration-200 ${
|
||||
field.value === 'ACTIVE' ? 'translate-x-4' : 'translate-x-0'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<span className="text-[11px] font-bold text-foreground">
|
||||
{field.value === 'ACTIVE' ? '적용 승인' : '적용 대기'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 p-2 bg-muted/60 border border-border/60 rounded-md h-[34px] cursor-not-allowed select-none">
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
className="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border-2 border-transparent transition-all duration-200 bg-blue-400/40 dark:bg-blue-600/30 cursor-not-allowed"
|
||||
>
|
||||
<span className="pointer-events-none block h-4 w-4 rounded-full bg-white/70 dark:bg-zinc-400 translate-x-4" />
|
||||
</button>
|
||||
<span className="text-[11px] text-muted-foreground font-semibold">상시 항상 적용</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="small" className="font-semibold">카드이름</Typography>
|
||||
<Input
|
||||
id="form-card-title"
|
||||
type="text"
|
||||
{...register('title')}
|
||||
placeholder="예: 최우수 등급 부여 카드"
|
||||
/>
|
||||
{errors.title && <p className="text-[10px] text-rose-500">{errors.title.message}</p>}
|
||||
</div>
|
||||
|
||||
{/* Script */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Typography as="label" variant="small" className="font-bold flex items-center gap-1.5">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-primary" />
|
||||
스크립트
|
||||
</Typography>
|
||||
<div className="text-[10px] text-muted-foreground bg-muted px-2 py-0.5 rounded border border-border">
|
||||
치환 변수 사용: {'{target_price}'}, {'{partner_name}'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="border border-border rounded-md overflow-hidden bg-background focus-within:border-foreground/30 transition-all">
|
||||
<div className="bg-muted/45 px-3 py-1.5 border-b border-border flex items-center justify-between text-[10px] text-muted-foreground select-none">
|
||||
<span>에디터</span>
|
||||
</div>
|
||||
<textarea
|
||||
id="form-card-script"
|
||||
{...register('scriptPreview')}
|
||||
rows={3}
|
||||
className="w-full p-3 bg-transparent text-xs leading-relaxed resize-none focus:outline-none font-sans border-none"
|
||||
placeholder="협상 중에 상대에게 발송할 멘트 스크립트를 기술하십시오."
|
||||
/>
|
||||
</div>
|
||||
{errors.scriptPreview && <p className="text-[10px] text-rose-500">{errors.scriptPreview.message}</p>}
|
||||
</div>
|
||||
|
||||
{/* Wildcard-only fields */}
|
||||
{isWildcard && (
|
||||
<div className="space-y-4 p-3 bg-muted/40 rounded border border-border">
|
||||
<Typography variant="label" className="font-bold text-[10px] block">와일드카드 세부조항</Typography>
|
||||
<div className="space-y-3 font-mono">
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="small" className="font-semibold">사용 조건</Typography>
|
||||
<Input
|
||||
id="form-card-trigger"
|
||||
type="text"
|
||||
{...register('triggerCondition')}
|
||||
placeholder="예: 원부자재 시세가 계약일 대조 3.5% 상회 시"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="small" className="font-semibold">메모</Typography>
|
||||
<Input
|
||||
id="form-card-memo"
|
||||
type="text"
|
||||
{...register('memo')}
|
||||
placeholder="예: 특정 원재료 포함 입찰에만 적용"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<div className="pt-4 flex items-center gap-2 border-t border-border mt-8">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="flex-1 py-1.5 border border-border rounded text-foreground cursor-pointer text-center"
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
id="form-card-submit"
|
||||
className="flex-1 py-1.5 bg-primary text-primary-foreground font-bold rounded hover:opacity-95 cursor-pointer text-center"
|
||||
>
|
||||
{mode === 'create' ? '저장' : '수정'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Edit3, Trash2 } from 'lucide-react';
|
||||
import { DataTable } from '@/components/ui/data-table';
|
||||
import type { NegotiationCard } from '../types';
|
||||
|
||||
type CardTableProps = {
|
||||
data: NegotiationCard[];
|
||||
onEdit: (card: NegotiationCard) => void;
|
||||
onDelete: (id: string, title: string) => void;
|
||||
};
|
||||
|
||||
export function CardTable({ data, onEdit, onDelete }: CardTableProps) {
|
||||
return (
|
||||
<DataTable
|
||||
data={data}
|
||||
rowKey={(card) => card.id}
|
||||
onRowClick={onEdit}
|
||||
empty="데이터가 없습니다."
|
||||
columns={[
|
||||
{
|
||||
header: '구분',
|
||||
headClassName: 'w-24',
|
||||
cell: (card) =>
|
||||
card.isWildcard ? (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-bold bg-rose-50 text-rose-700 dark:bg-rose-950/20 dark:text-rose-400 border border-rose-200/40">
|
||||
와일드카드
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-bold bg-blue-50 text-blue-700 dark:bg-blue-950/20 dark:text-blue-400 border border-blue-200/40">
|
||||
협상카드
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '카드번호',
|
||||
headClassName: 'w-28',
|
||||
cellClassName: 'font-mono font-semibold text-foreground',
|
||||
cell: (card) => card.code,
|
||||
},
|
||||
{
|
||||
header: '카드이름',
|
||||
headClassName: 'w-52',
|
||||
cell: (card) => (
|
||||
<>
|
||||
<div className="font-semibold text-foreground text-sm">{card.title}</div>
|
||||
{card.memo && (
|
||||
<div className="text-[10px] text-muted-foreground font-mono mt-0.5 max-w-[200px] truncate">
|
||||
{card.memo}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '스크립트',
|
||||
cellClassName: 'font-mono text-muted-foreground',
|
||||
cell: (card) => (
|
||||
<div className="line-clamp-2 bg-muted/20 p-2.5 rounded border border-border/30 text-[11px] leading-relaxed">
|
||||
{card.scriptPreview}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '사용 조건 (와일드 전용)',
|
||||
headClassName: 'w-40',
|
||||
cellClassName: 'font-mono text-xs font-semibold text-rose-600 dark:text-rose-400',
|
||||
cell: (card) => (card.isWildcard ? card.triggerCondition || '조건 없음' : '-'),
|
||||
},
|
||||
{
|
||||
header: '상태',
|
||||
align: 'center',
|
||||
headClassName: 'w-24',
|
||||
cell: (card) =>
|
||||
card.isWildcard ? (
|
||||
<span
|
||||
className={`inline-flex items-center px-2 py-0.5 text-[10px] font-semibold rounded-full border ${
|
||||
card.status === 'ACTIVE'
|
||||
? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/20 dark:text-emerald-400 border-emerald-300/40'
|
||||
: 'bg-amber-50 text-amber-700 dark:bg-amber-950/20 dark:text-amber-400 border-amber-300/45'
|
||||
}`}
|
||||
>
|
||||
{card.status === 'ACTIVE' ? '협상적용 가능' : '적용 대기(수동)'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground font-mono font-medium opacity-65">-</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '관리',
|
||||
align: 'center',
|
||||
headClassName: 'w-24',
|
||||
cell: (card) => (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onEdit(card);
|
||||
}}
|
||||
className="p-1.5 text-foreground hover:bg-muted rounded cursor-pointer transition-colors"
|
||||
title="수정"
|
||||
>
|
||||
<Edit3 size={14} />
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDelete(card.id, card.title);
|
||||
}}
|
||||
className="p-1.5 text-muted-foreground hover:bg-red-50 hover:text-red-500 rounded cursor-pointer transition-colors"
|
||||
title="삭제"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useState } from 'react';
|
||||
import type { NegotiationCard, CardTab } from '../types';
|
||||
|
||||
// 카드 목록의 탭(전체/협상/와일드) + 검색 필터 state와 파생 결과/카운트.
|
||||
export function useCardFilters(cards: NegotiationCard[]) {
|
||||
const [search, setSearch] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<CardTab>('ALL');
|
||||
|
||||
const filtered = cards.filter((card) => {
|
||||
const matchesTab =
|
||||
activeTab === 'ALL' || (activeTab === 'WILD' ? card.isWildcard : !card.isWildcard);
|
||||
const q = search.toLowerCase();
|
||||
const matchesSearch =
|
||||
card.title.toLowerCase().includes(q) ||
|
||||
card.code.toLowerCase().includes(q) ||
|
||||
card.scriptPreview.toLowerCase().includes(q);
|
||||
return matchesTab && matchesSearch;
|
||||
});
|
||||
|
||||
const counts = {
|
||||
all: cards.length,
|
||||
card: cards.filter((c) => !c.isWildcard).length,
|
||||
wild: cards.filter((c) => c.isWildcard).length,
|
||||
};
|
||||
|
||||
return { search, setSearch, activeTab, setActiveTab, filtered, counts };
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useState } from 'react';
|
||||
import type { NegotiationCard } from '@/types';
|
||||
import { generateSlateJSON } from '../types';
|
||||
|
||||
// 카드 폼이 넘기는 입력값(편집/생성 공통).
|
||||
export type CardInput = {
|
||||
title: string;
|
||||
code: string;
|
||||
scriptPreview: string;
|
||||
status: 'ACTIVE' | 'INACTIVE';
|
||||
isWildcard: boolean;
|
||||
triggerCondition?: string;
|
||||
memo?: string;
|
||||
};
|
||||
|
||||
// 협상카드 카탈로그 — 백엔드 미연동이라 로컬 state로만 CRUD(목업 제거됨, 빈 상태로 시작).
|
||||
// 와일드카드 전용 필드(triggerCondition/memo)는 isWildcard일 때만 보존한다.
|
||||
export function useCards() {
|
||||
const [cards, setCards] = useState<NegotiationCard[]>([]);
|
||||
|
||||
const toCard = (id: string, input: CardInput): NegotiationCard => ({
|
||||
id,
|
||||
isWildcard: input.isWildcard,
|
||||
code: input.code,
|
||||
title: input.title,
|
||||
scriptPreview: input.scriptPreview,
|
||||
editorScript: generateSlateJSON(input.scriptPreview),
|
||||
status: input.status,
|
||||
triggerCondition: input.isWildcard ? input.triggerCondition : undefined,
|
||||
memo: input.isWildcard ? input.memo : undefined,
|
||||
});
|
||||
|
||||
const createCard = (input: CardInput) => {
|
||||
setCards((prev) => [...prev, toCard(`card-${Date.now()}`, input)]);
|
||||
};
|
||||
|
||||
const updateCard = (id: string, input: CardInput) => {
|
||||
setCards((prev) => prev.map((c) => (c.id === id ? { ...c, ...toCard(id, input) } : c)));
|
||||
};
|
||||
|
||||
const deleteCard = (id: string) => {
|
||||
setCards((prev) => prev.filter((c) => c.id !== id));
|
||||
};
|
||||
|
||||
return { cards, createCard, updateCard, deleteCard };
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { NegotiationCard } from '@/types';
|
||||
|
||||
export type { NegotiationCard };
|
||||
|
||||
// 카드 목록 탭. 'ALL' 전체 / 'CARD' 일반 협상카드 / 'WILD' 와일드카드.
|
||||
export type CardTab = 'ALL' | 'CARD' | 'WILD';
|
||||
|
||||
// 평문 스크립트를 Slate JSON 노드로 변환(카드 저장 시 editorScript 생성).
|
||||
export function generateSlateJSON(previewText: string): unknown[] {
|
||||
return [
|
||||
{
|
||||
type: 'paragraph',
|
||||
children: [{ text: '카드 스크립트:\n' }, { text: previewText }],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// 신규 카드번호 자동 생성(종류에 따라 접두사 분기).
|
||||
export const generateCardCode = (isWildcard: boolean) =>
|
||||
`${isWildcard ? 'WILD' : 'CARD'}-NEW-${Math.floor(10 + Math.random() * 90)}`;
|
||||
@@ -0,0 +1,324 @@
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { Upload, X, FileSpreadsheet, CheckCircle2, Download } from 'lucide-react';
|
||||
import type { SupplierCreate } from '@/api/generated/model/supplierCreate';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { downloadExcel, parseCsv } from '@/lib/excel';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import type { Partner } from '../types';
|
||||
|
||||
// 엑셀에서 읽어온 원본 행(입력값만). status/message는 저장하지 않고 검증에서 파생한다.
|
||||
type RawRow = {
|
||||
id: string;
|
||||
rowNum: number;
|
||||
name: string;
|
||||
code: string;
|
||||
managerName: string;
|
||||
managerEmail: string;
|
||||
priority: string;
|
||||
};
|
||||
|
||||
type ValidatedRow = RawRow & { status: '정상' | '오류'; message: string };
|
||||
|
||||
// 업로드 양식 한 줄(예시 행)
|
||||
type TemplateRow = { name: string; code: string; managerName: string; managerEmail: string; priority: string };
|
||||
|
||||
type ExcelUploadModalProps = {
|
||||
open: boolean;
|
||||
partners: Partner[]; // 코드 중복 검사용
|
||||
onConfirm: (rows: SupplierCreate[]) => Promise<void>;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
// 행 검증 — 순수 함수. 우선순위 순으로 첫 위반 메시지를 매긴다.
|
||||
function validateRows(rows: RawRow[], partners: Partner[]): ValidatedRow[] {
|
||||
return rows.map((row) => {
|
||||
const fail = (message: string): ValidatedRow => ({ ...row, status: '오류', message });
|
||||
|
||||
if (!row.name.trim()) return fail('유효성 위반 - 협력사명을 입력해 주십시오.');
|
||||
if (!row.code.trim()) return fail('유효성 위반 - 식별코드를 입력해 주십시오.');
|
||||
|
||||
const dupInPartners = partners.some((p) => p.code === row.code && !p.deleted);
|
||||
const dupInExcel = rows.some((other) => other.id !== row.id && other.code === row.code);
|
||||
if (dupInPartners || dupInExcel) return fail('코드 중복 - 이미 존재하거나 목록 내 중복된 코드입니다.');
|
||||
|
||||
if (!row.managerEmail.trim() || !row.managerEmail.includes('@')) {
|
||||
return fail('이메일 형식 규격 외 - 올바른 이메일 주소(@ 포함)가 필요합니다.');
|
||||
}
|
||||
|
||||
return { ...row, status: '정상', message: '등록 적격 - 정합성 검증 통과' };
|
||||
});
|
||||
}
|
||||
|
||||
// 검증된(정상) 행 → 서버 생성 payload.
|
||||
function toSupplierCreate(row: RawRow): SupplierCreate {
|
||||
return {
|
||||
name: row.name,
|
||||
code: row.code,
|
||||
manager_name: row.managerName,
|
||||
manager_email: row.managerEmail,
|
||||
manager_contact_number: '010-0000-0000',
|
||||
priority: row.priority,
|
||||
};
|
||||
}
|
||||
|
||||
// 협력사 엑셀 일괄 업로드 모달. 파일 파싱·원본 행 state는 이 컴포넌트가 소유하고,
|
||||
// 검증은 렌더 시 validateRows로 파생한다. 실제 서버 등록은 onConfirm(검증된 행)으로 위임.
|
||||
export function ExcelUploadModal({ open, partners, onConfirm, onClose }: ExcelUploadModalProps) {
|
||||
const [excelFile, setExcelFile] = useState<string | null>(null);
|
||||
const [rows, setRows] = useState<RawRow[]>([]);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const validated = useMemo(() => validateRows(rows, partners), [rows, partners]);
|
||||
const validRows = validated.filter((r) => r.status === '정상');
|
||||
const validCount = validRows.length;
|
||||
const errorCount = validated.length - validCount;
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const close = () => {
|
||||
setExcelFile(null);
|
||||
setRows([]);
|
||||
onClose();
|
||||
};
|
||||
|
||||
// 업로드 양식(.csv) 다운로드 — 채워 넣을 컬럼 헤더 + 예시 1행 (lib/excel 재사용)
|
||||
const handleDownloadTemplate = () => {
|
||||
downloadExcel<TemplateRow>(
|
||||
'협력사_업로드_양식',
|
||||
[
|
||||
{ header: '협력사명', value: (r) => r.name },
|
||||
{ header: '식별코드', value: (r) => r.code },
|
||||
{ header: '담당자명', value: (r) => r.managerName },
|
||||
{ header: '담당자이메일', value: (r) => r.managerEmail },
|
||||
{ header: '우선순위', value: (r) => r.priority },
|
||||
],
|
||||
[{ name: '예시) (주)한빛정밀', code: 'PART-EXAMPLE-001', managerName: '김철수 과장', managerEmail: 'cs.kim@example.com', priority: 'HIGH' }],
|
||||
);
|
||||
};
|
||||
|
||||
// 업로드된 CSV를 파싱해 원본 행으로 적재(검증은 자동 파생). 헤더는 양식과 동일해야 함.
|
||||
const handleFile = async (file: File) => {
|
||||
const parsed = parseCsv(await file.text());
|
||||
const loaded: RawRow[] = parsed.map((r, i) => ({
|
||||
id: `row-${i + 1}`,
|
||||
rowNum: i + 2,
|
||||
name: r['협력사명'] ?? '',
|
||||
code: r['식별코드'] ?? '',
|
||||
managerName: r['담당자명'] ?? '',
|
||||
managerEmail: r['담당자이메일'] ?? '',
|
||||
priority: r['우선순위'] ?? 'MEDIUM',
|
||||
}));
|
||||
setExcelFile(file.name);
|
||||
setRows(loaded);
|
||||
};
|
||||
|
||||
// 인라인 편집 — 원본 필드만 갱신(재검증은 파생이 처리)
|
||||
const handleUpdateField = (id: string, field: 'name' | 'code' | 'managerName' | 'managerEmail', value: string) => {
|
||||
setRows((cur) => cur.map((row) => (row.id === id ? { ...row, [field]: value } : row)));
|
||||
};
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (validRows.length === 0) {
|
||||
showToast('정합성이 무결한 파트너 행이 존재하지 않습니다.', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await onConfirm(validRows.map(toSupplierCreate));
|
||||
showToast(`총 ${validRows.length}개 협력사가 서버에 일괄 등록되었습니다.`, 'success');
|
||||
close();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '엑셀 일괄 등록 실패', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
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">
|
||||
|
||||
{/* Modal Title */}
|
||||
<div className="flex items-center justify-between pb-4 border-b border-border">
|
||||
<div className="flex items-center gap-2 text-foreground">
|
||||
<FileSpreadsheet className="text-muted-foreground" size={20} />
|
||||
<Typography variant="h3">협력사 엑셀 일괄 검증 및 등록</Typography>
|
||||
</div>
|
||||
<button
|
||||
onClick={close}
|
||||
className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* File select + drop */}
|
||||
<div className="my-6">
|
||||
{!excelFile ? (
|
||||
<div
|
||||
onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
const file = e.dataTransfer.files?.[0];
|
||||
if (file) handleFile(file);
|
||||
}}
|
||||
className={`border-2 border-dashed rounded-lg p-8 flex flex-col items-center justify-center transition-colors ${
|
||||
isDragging ? 'border-primary bg-primary/10' : 'border-border bg-muted/30'
|
||||
}`}
|
||||
>
|
||||
<Upload size={32} className="text-muted-foreground mb-3" />
|
||||
<Typography variant="small" className="font-semibold">
|
||||
협력사 리스트 엑셀 파일을 업로드해 주십시오
|
||||
</Typography>
|
||||
<Typography variant="muted" className="text-[10px] mt-1.5 mb-4">
|
||||
협력사 코드 중복 및 필수 항목 검사를 수행합니다.
|
||||
</Typography>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
id="excel-partners-file-input"
|
||||
accept=".csv,.xls,.xlsx"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) handleFile(file);
|
||||
}}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
id="excel-partners-simulation-button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="py-1.5 px-3 bg-foreground text-background text-xs font-semibold rounded cursor-pointer hover:opacity-95"
|
||||
>
|
||||
엑셀 파일 업로드하기
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
id="excel-partners-template-download-button"
|
||||
onClick={handleDownloadTemplate}
|
||||
className="mt-2.5 flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground underline underline-offset-2 cursor-pointer"
|
||||
>
|
||||
<Download size={12} />
|
||||
업로드 양식(.csv) 다운로드
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* File meta */}
|
||||
<div className="flex items-center justify-between p-3 rounded bg-emerald-500/10 border border-emerald-500/30 text-xs">
|
||||
<div className="flex items-center gap-2 text-foreground">
|
||||
<CheckCircle2 className="text-emerald-500" size={16} />
|
||||
<span>{excelFile}</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground font-mono">{validated.length}개 데이터 행 검출</span>
|
||||
</div>
|
||||
|
||||
{/* Previews table and validation */}
|
||||
<div className="space-y-1.5">
|
||||
<span className="text-xs font-bold text-foreground block">엑셀 정밀 유효값 진단</span>
|
||||
|
||||
<div className="border border-border rounded overflow-hidden max-h-60 overflow-y-auto">
|
||||
<Table className="w-full text-left font-mono text-[11px] border-collapse bg-background">
|
||||
<TableHeader className="bg-muted text-muted-foreground text-[10px] border-b border-border">
|
||||
<TableRow>
|
||||
<TableHead className="p-2 font-semibold w-12 text-center">행</TableHead>
|
||||
<TableHead className="p-2 font-semibold">협력사명 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold">협력사코드 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold">담당자명 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold">담당자 이메일 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold text-center w-16">자격</TableHead>
|
||||
<TableHead className="p-2 font-semibold">진단 내용 (직접 수정가능)</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="divide-y divide-border">
|
||||
{validated.map((row) => (
|
||||
<TableRow key={row.id} className={row.status === '오류' ? 'bg-red-500/5 hover:bg-red-500/10' : 'bg-emerald-500/5 hover:bg-emerald-500/10'}>
|
||||
<TableCell className="p-2 text-center text-muted-foreground">{row.rowNum}</TableCell>
|
||||
<TableCell className="p-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="bg-muted/20 hover:bg-muted/50 text-foreground font-semibold"
|
||||
value={row.name}
|
||||
onChange={(e) => handleUpdateField(row.id, 'name', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="bg-muted/20 hover:bg-muted/50 text-foreground font-mono"
|
||||
value={row.code}
|
||||
onChange={(e) => handleUpdateField(row.id, 'code', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="bg-muted/20 hover:bg-muted/50 text-foreground"
|
||||
value={row.managerName}
|
||||
onChange={(e) => handleUpdateField(row.id, 'managerName', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="bg-muted/20 hover:bg-muted/50 text-foreground font-mono"
|
||||
value={row.managerEmail}
|
||||
onChange={(e) => handleUpdateField(row.id, 'managerEmail', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2 text-center">
|
||||
<span className={`px-1.5 py-0.5 rounded text-[9px] font-bold block ${
|
||||
row.status === '정상'
|
||||
? 'bg-emerald-100 text-emerald-800 border border-emerald-300 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-800/80'
|
||||
: 'bg-red-100 text-red-800 border border-red-300 dark:bg-rose-950/40 dark:text-rose-300 dark:border-rose-950'
|
||||
}`}>
|
||||
{row.status}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className={`p-2 font-mono text-[10px] ${row.status === '오류' ? 'text-rose-500' : 'text-emerald-600'}`}>
|
||||
{row.message}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Excel footer */}
|
||||
<div className="flex items-center justify-between pt-4 border-t border-border mt-6 text-xs bg-muted/40 p-3 rounded">
|
||||
<span className="font-mono text-muted-foreground">
|
||||
적격 대상사: {validCount}개소 // 비적격 차단: {errorCount}개소
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
className="py-1.5 px-3 border border-border rounded hover:bg-muted text-foreground cursor-pointer text-xs"
|
||||
>
|
||||
중단
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
id="excel-partners-confirm-button"
|
||||
disabled={validCount === 0}
|
||||
onClick={handleConfirm}
|
||||
className="py-1.5 px-4 bg-primary text-primary-foreground font-bold rounded hover:opacity-95 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-xs"
|
||||
>
|
||||
적격 협력사 추가 (총 {validCount}개사)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
import type { SupplierCreate } from '@/api/generated/model/supplierCreate';
|
||||
import type { SupplierUpdate } from '@/api/generated/model/supplierUpdate';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Sheet } from '@/components/ui/sheet';
|
||||
import { type Partner, priorityOptions } from '../types';
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().trim().min(1, '회사명/협력사명을 작성해 주십시오.'),
|
||||
code: z.string().trim().min(1, '협력사코드를 입력해 주십시오.'),
|
||||
managerName: z.string().trim().min(1, '담당자명을 입력해 주십시오.'),
|
||||
managerEmail: z.string().trim().email('정확한 담당자 이메일 형식을 점검해 주십시오.'),
|
||||
managerPhone: z.string().trim().min(1, '담당자 연락처를 입력해 주십시오.'),
|
||||
priority: z.string(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
type PartnerFormSheetProps = {
|
||||
open: boolean;
|
||||
mode: 'create' | 'edit';
|
||||
partner: Partner | null; // edit 모드일 때 초기값 출처
|
||||
onCreate: (data: SupplierCreate) => Promise<void>;
|
||||
onUpdate: (supplierId: string, data: SupplierUpdate) => Promise<void>;
|
||||
onDelete: (supplierId: string, name: string) => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
// mode/partner로 폼 초기값 산출. create는 기본값, edit는 partner에서.
|
||||
function buildDefaults(mode: 'create' | 'edit', partner: Partner | null): FormValues {
|
||||
if (mode === 'edit' && partner) {
|
||||
return {
|
||||
name: partner.name ?? '',
|
||||
code: partner.code || '',
|
||||
managerName: partner.manager_name || '',
|
||||
managerEmail: partner.manager_email || '',
|
||||
managerPhone: partner.manager_contact_number || '',
|
||||
priority: partner.priority || 'MEDIUM',
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: '',
|
||||
code: `PART-CORP-${Math.floor(100 + Math.random() * 900)}`,
|
||||
managerName: '',
|
||||
managerEmail: '',
|
||||
managerPhone: '010-',
|
||||
priority: 'MEDIUM',
|
||||
};
|
||||
}
|
||||
|
||||
const inputClass = 'text-foreground text-xs';
|
||||
|
||||
export function PartnerFormSheet({
|
||||
open,
|
||||
mode,
|
||||
partner,
|
||||
onCreate,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
onClose,
|
||||
}: PartnerFormSheetProps) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: buildDefaults(mode, partner),
|
||||
});
|
||||
|
||||
const onValid = async (v: FormValues) => {
|
||||
const common = {
|
||||
name: v.name,
|
||||
code: v.code,
|
||||
manager_name: v.managerName,
|
||||
manager_email: v.managerEmail,
|
||||
manager_contact_number: v.managerPhone,
|
||||
priority: v.priority,
|
||||
};
|
||||
|
||||
if (mode === 'create') {
|
||||
try {
|
||||
await onCreate(common as SupplierCreate);
|
||||
showToast('신규 협력사가 등록되었습니다.', 'success');
|
||||
onClose();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '협력사 등록 실패', 'error');
|
||||
}
|
||||
} else if (partner) {
|
||||
try {
|
||||
await onUpdate(partner.supplier_id, common as SupplierUpdate);
|
||||
showToast('협력사 정보가 최신화되었습니다.', 'success');
|
||||
onClose();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '협력사 수정 실패', 'error');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={open}
|
||||
title={mode === 'create' ? '신규 협력사 등록' : '협력사 정보 관리'}
|
||||
onClose={onClose}
|
||||
>
|
||||
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
|
||||
{/* Partner Name */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">협력사명</Typography>
|
||||
<Input
|
||||
id="form-partner-name"
|
||||
type="text"
|
||||
{...register('name')}
|
||||
className={inputClass}
|
||||
placeholder="예: (주)대현정밀부품"
|
||||
/>
|
||||
{errors.name && <p className="text-[10px] text-rose-500">{errors.name.message}</p>}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Code */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">협력사코드</Typography>
|
||||
<Input
|
||||
id="form-partner-code"
|
||||
type="text"
|
||||
{...register('code')}
|
||||
className={inputClass}
|
||||
placeholder="PART-XXXX"
|
||||
/>
|
||||
{errors.code && <p className="text-[10px] text-rose-500">{errors.code.message}</p>}
|
||||
</div>
|
||||
{/* Priority */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">우선 선정 대상자</Typography>
|
||||
<select
|
||||
id="form-partner-priority"
|
||||
{...register('priority')}
|
||||
className={`w-full p-2 bg-background border border-border rounded ${inputClass} cursor-pointer`}
|
||||
>
|
||||
{priorityOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>{opt.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Manager Name */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">담당자명</Typography>
|
||||
<Input
|
||||
id="form-partner-manager"
|
||||
type="text"
|
||||
{...register('managerName')}
|
||||
className={inputClass}
|
||||
placeholder="김민우 책임과장"
|
||||
/>
|
||||
{errors.managerName && <p className="text-[10px] text-rose-500">{errors.managerName.message}</p>}
|
||||
</div>
|
||||
|
||||
{/* Manager Email */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">담당자 이메일</Typography>
|
||||
<Input
|
||||
id="form-partner-email"
|
||||
type="email"
|
||||
{...register('managerEmail')}
|
||||
className={inputClass}
|
||||
placeholder="manager@company.co.kr"
|
||||
/>
|
||||
{errors.managerEmail && <p className="text-[10px] text-rose-500">{errors.managerEmail.message}</p>}
|
||||
</div>
|
||||
|
||||
{/* Manager Phone */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">담당자 연락처</Typography>
|
||||
<Input
|
||||
id="form-partner-phone"
|
||||
type="text"
|
||||
{...register('managerPhone')}
|
||||
className={inputClass}
|
||||
placeholder="010-XXXX-XXXX"
|
||||
/>
|
||||
{errors.managerPhone && <p className="text-[10px] text-rose-500">{errors.managerPhone.message}</p>}
|
||||
</div>
|
||||
|
||||
{/* Buttons wrapper */}
|
||||
<div className="pt-4 flex items-center gap-2 border-t border-border mt-8 justify-between">
|
||||
{mode === 'edit' && partner && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onDelete(partner.supplier_id, partner.name);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
<Trash2 />
|
||||
삭제
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex items-center gap-2 flex-1 justify-end">
|
||||
<Button type="button" variant="outline" size="sm" onClick={onClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" size="sm" disabled={isSubmitting}>
|
||||
{mode === 'create' ? '신규 파트너 등록' : '변경사항 저장'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { DataTable } from '@/components/ui/data-table';
|
||||
import { TablePagination } from '@/components/ui/table-pagination';
|
||||
import type { Partner } from '../types';
|
||||
|
||||
type PartnerTableProps = {
|
||||
data: Partner[];
|
||||
onRowClick: (part: Partner) => void;
|
||||
page: number;
|
||||
totalPages: number;
|
||||
totalCount: number;
|
||||
pageSize: number;
|
||||
onPageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
// 우선순위 배지 색상 — HIGH(빨강)/MEDIUM(주황)/그외(회색)
|
||||
const priorityBadgeClass = (priority?: string | null) =>
|
||||
priority === 'HIGH'
|
||||
? 'bg-red-50 text-red-700 dark:bg-rose-950/20 dark:text-rose-400 border border-red-200'
|
||||
: priority === 'MEDIUM'
|
||||
? 'bg-amber-50 text-amber-700 dark:bg-amber-950/20 dark:text-amber-400 border border-amber-200'
|
||||
: 'bg-zinc-100 text-zinc-600 border border-zinc-300';
|
||||
|
||||
export function PartnerTable({
|
||||
data,
|
||||
onRowClick,
|
||||
page,
|
||||
totalPages,
|
||||
totalCount,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
}: PartnerTableProps) {
|
||||
return (
|
||||
<DataTable
|
||||
data={data}
|
||||
rowKey={(part) => part.supplier_id}
|
||||
onRowClick={onRowClick}
|
||||
empty="협약된 가용 B2B 파트너사가 존재하지 않습니다."
|
||||
footer={
|
||||
<TablePagination
|
||||
page={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={totalCount}
|
||||
pageSize={pageSize}
|
||||
onPageChange={onPageChange}
|
||||
label="연동 파트너사"
|
||||
unit="개사"
|
||||
/>
|
||||
}
|
||||
columns={[
|
||||
{
|
||||
header: '협력사명',
|
||||
align: 'left',
|
||||
headClassName: 'w-2/5',
|
||||
cell: (part) => (
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="h-8 w-8 flex-shrink-0 rounded-full bg-muted border border-border flex items-center justify-center font-bold text-muted-foreground">
|
||||
{(part.name ?? '').charAt(0)}
|
||||
</div>
|
||||
<span className="font-bold text-sm text-foreground">{part.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '협력사코드',
|
||||
align: 'left',
|
||||
cellClassName: 'font-mono font-medium text-muted-foreground',
|
||||
cell: (part) => part.code,
|
||||
},
|
||||
{
|
||||
header: '담당자명 / 담당자 이메일 / 연락처',
|
||||
align: 'left',
|
||||
cell: (part) => (
|
||||
<div className="space-y-0.5 font-mono text-xs">
|
||||
<div className="text-foreground font-semibold">{part.manager_name}</div>
|
||||
<div className="text-[10px] text-muted-foreground">
|
||||
{part.manager_email} / {part.manager_contact_number}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '우선 선정 대상자',
|
||||
align: 'center',
|
||||
cell: (part) => (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`inline-flex items-center px-2 py-0.5 text-[10px] font-bold rounded-full ${priorityBadgeClass(part.priority)}`}
|
||||
>
|
||||
{part.priority}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useState } from 'react';
|
||||
import type { Partner } from '../types';
|
||||
|
||||
const ITEMS_PER_PAGE = 5;
|
||||
|
||||
// 협력사 목록에 대한 검색/우선순위/페이지네이션 UI state + 파생 결과.
|
||||
// 검색·우선순위 변경 시 1페이지로 리셋한다.
|
||||
export function usePartnerFilters(partners: Partner[]) {
|
||||
const [search, setSearchRaw] = useState('');
|
||||
const [priorityFilter, setPriorityFilterRaw] = useState('ALL');
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const setSearch = (v: string) => {
|
||||
setSearchRaw(v);
|
||||
setPage(1);
|
||||
};
|
||||
const setPriorityFilter = (v: string) => {
|
||||
setPriorityFilterRaw(v);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const filtered = partners.filter((part) => {
|
||||
if (part.deleted) return false; // soft-deleted 제외
|
||||
const q = search.toLowerCase();
|
||||
const matchesSearch =
|
||||
(part.name ?? '').toLowerCase().includes(q) ||
|
||||
(part.code ? part.code.toLowerCase().includes(q) : false) ||
|
||||
(part.manager_name ? part.manager_name.toLowerCase().includes(q) : false);
|
||||
const matchesPriority = priorityFilter === 'ALL' || part.priority === priorityFilter;
|
||||
return matchesSearch && matchesPriority;
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(filtered.length / ITEMS_PER_PAGE) || 1;
|
||||
const paginated = filtered.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
|
||||
|
||||
return {
|
||||
search,
|
||||
setSearch,
|
||||
priorityFilter,
|
||||
setPriorityFilter,
|
||||
page,
|
||||
setPage,
|
||||
paginated,
|
||||
totalPages,
|
||||
totalCount: filtered.length,
|
||||
itemsPerPage: ITEMS_PER_PAGE,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
useListSuppliers,
|
||||
createSupplier,
|
||||
updateSupplier,
|
||||
deleteSupplier,
|
||||
getListSuppliersQueryKey,
|
||||
} from '@/api/generated/supplier/supplier';
|
||||
import type { SupplierResponse } from '@/api/generated/model/supplierResponse';
|
||||
import type { SupplierCreate } from '@/api/generated/model/supplierCreate';
|
||||
import type { SupplierUpdate } from '@/api/generated/model/supplierUpdate';
|
||||
import type { Partner } from '../types';
|
||||
|
||||
const LIST_PARAMS = { size: 100 };
|
||||
|
||||
// 협력사 서버 데이터 + CRUD. orval 뮤테이션 호출 후 목록 쿼리 무효화(재조회).
|
||||
// 실패 시 throw → 호출부에서 toast 처리.
|
||||
export function usePartners() {
|
||||
const queryClient = useQueryClient();
|
||||
const suppliersQuery = useListSuppliers(LIST_PARAMS);
|
||||
|
||||
const refresh = () =>
|
||||
queryClient.invalidateQueries({ queryKey: getListSuppliersQueryKey(LIST_PARAMS) });
|
||||
|
||||
const createPartner = async (data: SupplierCreate) => {
|
||||
await createSupplier(data);
|
||||
await refresh();
|
||||
};
|
||||
const updatePartner = async (supplierId: string, data: SupplierUpdate) => {
|
||||
await updateSupplier(supplierId, data);
|
||||
await refresh();
|
||||
};
|
||||
const deletePartner = async (supplierId: string) => {
|
||||
await deleteSupplier(supplierId);
|
||||
await refresh();
|
||||
};
|
||||
// 엑셀 일괄 등록 — 검증된 행들을 순차 생성 후 한 번만 재조회.
|
||||
const bulkCreate = async (rows: SupplierCreate[]) => {
|
||||
for (const row of rows) {
|
||||
await createSupplier(row);
|
||||
}
|
||||
await refresh();
|
||||
};
|
||||
|
||||
// 서버 SupplierResponse → UI Partner (그대로 + id 별칭만)
|
||||
const suppliers =
|
||||
(suppliersQuery.data as { data?: { data?: { suppliers?: SupplierResponse[] } } } | undefined)
|
||||
?.data?.data?.suppliers ?? [];
|
||||
const partners: Partner[] = suppliers.map((sp) => ({ ...sp, id: sp.supplier_id }));
|
||||
|
||||
return { partners, createPartner, updatePartner, deletePartner, bulkCreate, refresh, suppliersQuery };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { SupplierResponse } from '@/api/generated/model/supplierResponse';
|
||||
|
||||
// UI에서 쓰는 협력사 타입. 서버 SupplierResponse에 화면 전용 파생 필드만 얹는다.
|
||||
// (level/rank/status 등 서버 미연동 가짜 필드는 두지 않는다 — 표시 가능한 건 priority뿐.)
|
||||
export type Partner = SupplierResponse & {
|
||||
deleted?: boolean;
|
||||
id?: string;
|
||||
};
|
||||
|
||||
// 우선순위 필터 목록. 'ALL'은 필터 전용(폼에서는 제외).
|
||||
export const prioritiesList = ['ALL', 'HIGH', 'MEDIUM', 'LOW'];
|
||||
|
||||
// 폼 우선순위 선택지(라벨 포함).
|
||||
export const priorityOptions: { value: string; label: string }[] = [
|
||||
{ value: 'HIGH', label: 'HIGH (핵심 조달처)' },
|
||||
{ value: 'MEDIUM', label: 'MEDIUM (일반 벤더)' },
|
||||
{ value: 'LOW', label: 'LOW (서브 보조처)' },
|
||||
];
|
||||
@@ -0,0 +1,339 @@
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { Upload, X, FileSpreadsheet, CheckCircle2, Download } from 'lucide-react';
|
||||
import type { ItemCreate } from '@/api/generated/model/itemCreate';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { downloadExcel, parseCsv } from '@/lib/excel';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import type { Product } from '../types';
|
||||
|
||||
// 엑셀에서 읽어온 원본 행(입력값만). status/message는 저장하지 않고 검증에서 파생한다.
|
||||
type RawRow = {
|
||||
id: string;
|
||||
rowNum: number;
|
||||
name: string;
|
||||
code: string;
|
||||
price: number;
|
||||
minPrice: number;
|
||||
};
|
||||
|
||||
// 검증 결과가 붙은 행. UI는 이걸 그린다.
|
||||
type ValidatedRow = RawRow & { status: '정상' | '오류'; message: string };
|
||||
|
||||
// 업로드 양식 한 줄(예시 행)
|
||||
type TemplateRow = { name: string; code: string; price: number; minPrice: number };
|
||||
|
||||
type ExcelUploadModalProps = {
|
||||
open: boolean;
|
||||
products: Product[]; // 코드 중복 검사용
|
||||
onConfirm: (rows: ItemCreate[]) => Promise<void>;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
// 행 검증 — 순수 함수. 우선순위 순으로 첫 위반 메시지를 매긴다. (상태에 저장하지 않고 렌더에서 파생)
|
||||
function validateRows(rows: RawRow[], products: Product[]): ValidatedRow[] {
|
||||
return rows.map((row) => {
|
||||
const fail = (message: string): ValidatedRow => ({ ...row, status: '오류', message });
|
||||
|
||||
if (!row.name.trim()) return fail('유효성 위반 - 상품명을 입력해 주십시오.');
|
||||
if (!row.code.trim()) return fail('유효성 위반 - 상품코드를 입력해 주십시오.');
|
||||
|
||||
const dupInProducts = products.some((p) => p.code === row.code && !p.deleted);
|
||||
const dupInExcel = rows.some((other) => other.id !== row.id && other.code === row.code);
|
||||
if (dupInProducts || dupInExcel) return fail('코드 중복 - 이미 존재하거나 목록 내 중복된 코드입니다.');
|
||||
|
||||
if (row.price <= 0) return fail('유효성 위반 - 상품 단가는 0보다 커야 합니다.');
|
||||
if (row.minPrice > row.price) return fail('유효성 위반 - 최저 한도가 상품 단가보다 큽니다.');
|
||||
|
||||
return { ...row, status: '정상', message: '등록 적격 - 정합성 검증 통과' };
|
||||
});
|
||||
}
|
||||
|
||||
// 검증된(정상) 행 → 서버 생성 payload. 엑셀 업로드 공통 기본값 적용.
|
||||
function toItemCreate(row: RawRow): ItemCreate {
|
||||
return {
|
||||
name: row.name,
|
||||
code: row.code,
|
||||
category: '자동화설비',
|
||||
price: row.price,
|
||||
model_name: 'EXCEL-LOADED',
|
||||
spec: '엑셀 일괄 업로드',
|
||||
manufacturer: '벌크 대리 수급처',
|
||||
made_in: '미지정',
|
||||
quantity_unit: 'EA',
|
||||
delivery_type: '벌크 대중 물류',
|
||||
moq: '10 EA',
|
||||
lead_time: 14,
|
||||
vat_yn: true,
|
||||
delivery_fee_yn: false,
|
||||
internet_lowest_price_yn: false,
|
||||
};
|
||||
}
|
||||
|
||||
// 상품 엑셀 일괄 업로드 모달. 파일 파싱(목업)·원본 행 state는 이 컴포넌트가 소유하고,
|
||||
// 검증은 렌더 시 validateRows로 파생한다. 실제 서버 등록은 onConfirm(검증된 행)으로 위임.
|
||||
export function ExcelUploadModal({ open, products, onConfirm, onClose }: ExcelUploadModalProps) {
|
||||
const [excelFile, setExcelFile] = useState<string | null>(null);
|
||||
const [rows, setRows] = useState<RawRow[]>([]);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// 파생: 검증 결과 + 카운트 (state로 저장하지 않음)
|
||||
const validated = useMemo(() => validateRows(rows, products), [rows, products]);
|
||||
const validRows = validated.filter((r) => r.status === '정상');
|
||||
const validCount = validRows.length;
|
||||
const errorCount = validated.length - validCount;
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const close = () => {
|
||||
setExcelFile(null);
|
||||
setRows([]);
|
||||
onClose();
|
||||
};
|
||||
|
||||
// 업로드 양식(.csv) 다운로드 — 채워 넣을 컬럼 헤더 + 예시 1행 (lib/excel 재사용)
|
||||
const handleDownloadTemplate = () => {
|
||||
downloadExcel<TemplateRow>(
|
||||
'상품_업로드_양식',
|
||||
[
|
||||
{ header: '상품명', value: (r) => r.name },
|
||||
{ header: '상품코드', value: (r) => r.code },
|
||||
{ header: '상품 단가', value: (r) => r.price },
|
||||
{ header: '최저한도', value: (r) => r.minPrice },
|
||||
],
|
||||
[{ name: '예시) 고용량 배터리 팩', code: 'PROD-EXAMPLE-001', price: 1000000, minPrice: 830000 }],
|
||||
);
|
||||
};
|
||||
|
||||
// 업로드된 CSV를 파싱해 원본 행으로 적재(검증은 자동 파생). 헤더는 양식과 동일해야 함.
|
||||
const handleFile = async (file: File) => {
|
||||
const parsed = parseCsv(await file.text());
|
||||
const loaded: RawRow[] = parsed.map((r, i) => ({
|
||||
id: `row-${i + 1}`,
|
||||
rowNum: i + 2,
|
||||
name: r['상품명'] ?? '',
|
||||
code: r['상품코드'] ?? '',
|
||||
price: Number(r['상품 단가']) || 0,
|
||||
minPrice: Number(r['최저한도']) || 0,
|
||||
}));
|
||||
setExcelFile(file.name);
|
||||
setRows(loaded);
|
||||
};
|
||||
|
||||
// 인라인 편집 — 원본 필드만 갱신(재검증은 파생이 처리)
|
||||
const handleUpdateField = (id: string, field: 'name' | 'code' | 'price' | 'minPrice', value: string) => {
|
||||
setRows((cur) =>
|
||||
cur.map((row) => {
|
||||
if (row.id !== id) return row;
|
||||
if (field === 'price' || field === 'minPrice') {
|
||||
return { ...row, [field]: Math.max(0, parseInt(value, 10) || 0) };
|
||||
}
|
||||
return { ...row, [field]: value };
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (validRows.length === 0) {
|
||||
showToast('정상으로 분류된 행이 존재하지 않아 업로드가 불가합니다.', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await onConfirm(validRows.map(toItemCreate));
|
||||
showToast(`총 ${validRows.length}개 상품이 서버에 일괄 등록되었습니다.`, 'success');
|
||||
close();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '엑셀 일괄 등록 실패', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
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">
|
||||
|
||||
{/* Modal Title */}
|
||||
<div className="flex items-center justify-between pb-4 border-b border-border">
|
||||
<div className="flex items-center gap-2 text-foreground">
|
||||
<FileSpreadsheet className="text-muted-foreground" size={20} />
|
||||
<Typography variant="h3">상품 엑셀 일괄 업로드</Typography>
|
||||
</div>
|
||||
<button
|
||||
onClick={close}
|
||||
className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Manual file select mock */}
|
||||
<div className="my-6">
|
||||
{!excelFile ? (
|
||||
<div
|
||||
onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
const file = e.dataTransfer.files?.[0];
|
||||
if (file) handleFile(file);
|
||||
}}
|
||||
className={`border-2 border-dashed rounded-lg p-8 flex flex-col items-center justify-center transition-colors ${
|
||||
isDragging ? 'border-primary bg-primary/10' : 'border-border bg-muted/30'
|
||||
}`}
|
||||
>
|
||||
<Upload size={32} className="text-muted-foreground mb-3" />
|
||||
<Typography variant="small" className="font-semibold">
|
||||
상품 엑셀 파일을 업로드해 주십시오
|
||||
</Typography>
|
||||
<Typography variant="muted" className="text-[10px] mt-1.5 mb-4">
|
||||
상품 코드 중복 및 필수 항목 검사를 수행합니다.
|
||||
</Typography>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
id="excel-file-input"
|
||||
accept=".csv,.xls,.xlsx"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) handleFile(file);
|
||||
}}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
id="excel-import-simulate-button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="py-1.5 px-3 bg-foreground text-background text-xs font-semibold rounded cursor-pointer hover:opacity-95"
|
||||
>
|
||||
엑셀 파일 업로드하기
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
id="excel-template-download-button"
|
||||
onClick={handleDownloadTemplate}
|
||||
className="mt-2.5 flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground underline underline-offset-2 cursor-pointer"
|
||||
>
|
||||
<Download size={12} />
|
||||
업로드 양식(.csv) 다운로드
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* File meta */}
|
||||
<div className="flex items-center justify-between p-3 rounded bg-emerald-500/10 border border-emerald-500/30 text-xs">
|
||||
<div className="flex items-center gap-2 text-foreground">
|
||||
<CheckCircle2 className="text-emerald-500" size={16} />
|
||||
<span>{excelFile}</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground font-mono">{validated.length}개 데이터 행 검출</span>
|
||||
</div>
|
||||
|
||||
{/* Previews table and validation */}
|
||||
<div className="space-y-1.5">
|
||||
<span className="text-xs font-bold text-foreground block">정합성 검출 미리보기</span>
|
||||
|
||||
<div className="border border-border rounded overflow-hidden max-h-60 overflow-y-auto">
|
||||
<Table className="w-full text-left font-mono text-[11px] border-collapse bg-background">
|
||||
<TableHeader className="bg-muted text-muted-foreground text-[10px] border-b border-border">
|
||||
<TableRow>
|
||||
<TableHead className="p-2 font-semibold">행(Row)</TableHead>
|
||||
<TableHead className="p-2 font-semibold">상품명 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold">상품코드 *</TableHead>
|
||||
<TableHead className="p-2 font-semibold text-right">상품 단가 (₩) *</TableHead>
|
||||
<TableHead className="p-2 font-semibold text-right">최저한도 (₩) *</TableHead>
|
||||
<TableHead className="p-2 font-semibold text-center">자격</TableHead>
|
||||
<TableHead className="p-2 font-semibold">진단 내용 (직접 수정가능)</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="divide-y divide-border">
|
||||
{validated.map((row) => (
|
||||
<TableRow key={row.id} className={row.status === '오류' ? 'bg-red-500/5 hover:bg-red-500/10' : 'bg-emerald-500/5 hover:bg-emerald-500/10'}>
|
||||
<TableCell className="p-2 text-muted-foreground">{row.rowNum}</TableCell>
|
||||
<TableCell className="p-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="bg-muted/20 hover:bg-muted/50 text-foreground font-semibold"
|
||||
value={row.name}
|
||||
onChange={(e) => handleUpdateField(row.id, 'name', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2">
|
||||
<Input
|
||||
type="text"
|
||||
className="bg-muted/20 hover:bg-muted/50 text-foreground font-mono"
|
||||
value={row.code}
|
||||
onChange={(e) => handleUpdateField(row.id, 'code', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2 text-right">
|
||||
<Input
|
||||
type="number"
|
||||
className="w-24 bg-muted/20 hover:bg-muted/50 text-right font-mono"
|
||||
value={row.price}
|
||||
onChange={(e) => handleUpdateField(row.id, 'price', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2 text-right">
|
||||
<Input
|
||||
type="number"
|
||||
className="w-24 bg-muted/20 hover:bg-muted/50 text-right font-mono"
|
||||
value={row.minPrice}
|
||||
onChange={(e) => handleUpdateField(row.id, 'minPrice', e.target.value)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="p-2 text-center">
|
||||
<span className={`px-1.5 py-0.5 rounded text-[9px] font-bold block ${
|
||||
row.status === '정상'
|
||||
? 'bg-emerald-100 text-emerald-800 border border-emerald-300 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-800/80'
|
||||
: 'bg-red-100 text-red-800 border border-red-300 dark:bg-rose-950/40 dark:text-rose-300 dark:border-rose-950'
|
||||
}`}>
|
||||
{row.status}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className={`p-2 font-mono text-[10px] ${row.status === '오류' ? 'text-rose-500' : 'text-emerald-600'}`}>
|
||||
{row.message}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Excel footer */}
|
||||
<div className="flex items-center justify-between pt-4 border-t border-border mt-6 text-xs bg-muted/40 p-3 rounded">
|
||||
<span className="font-mono text-muted-foreground">
|
||||
정상 적격 수치: {validCount}개 // 오류 행 수치: {errorCount}개
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
className="py-1.5 px-3 border border-border rounded hover:bg-muted text-foreground cursor-pointer text-xs"
|
||||
>
|
||||
취소하기
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
id="excel-final-confirm-button"
|
||||
disabled={validCount === 0}
|
||||
onClick={handleConfirm}
|
||||
className="py-1.5 px-4 bg-primary text-primary-foreground font-bold rounded hover:opacity-95 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-xs"
|
||||
>
|
||||
적격 상품(총 {validCount}개) 최종 전송
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { Globe, X, AlertCircle, Loader2, Cpu, RefreshCw } from 'lucide-react';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { Product } from '../types';
|
||||
|
||||
type PriceUpdateModalProps = {
|
||||
open: boolean;
|
||||
products: Product[];
|
||||
selectedIds: string[];
|
||||
onDone: () => void; // 완료 시 선택 해제
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
// 인터넷 최저가 실시간 수집 데모 모달. 크롤링 진행 state는 이 컴포넌트가 소유한다.
|
||||
// NOTE: 서버 미연동 — 진행 애니메이션/로그만 데모.
|
||||
export function PriceUpdateModal({ open, products, selectedIds, onDone, onClose }: PriceUpdateModalProps) {
|
||||
const [isCrawling, setIsCrawling] = useState(false);
|
||||
const [crawlingProgress, setCrawlingProgress] = useState(0);
|
||||
const [crawlerLogs, setCrawlerLogs] = useState<string[]>([]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const handleStartCrawling = () => {
|
||||
if (selectedIds.length === 0) {
|
||||
toast.error('업데이트할 상품을 1개 이상 선택해 주십시오.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCrawling(true);
|
||||
setCrawlingProgress(10);
|
||||
setCrawlerLogs([
|
||||
'[System] 실시간 최저가 수집용 웹 크롤러 엔진 가동...',
|
||||
'[System] API Endpoint: https://api.commerce-crawler.co.kr/v2/itemsync',
|
||||
`[Target] 선택된 ${selectedIds.length}개 상품의 고유 코드 및 품목 매핑 중...`,
|
||||
]);
|
||||
|
||||
// Fast simulation timers
|
||||
setTimeout(() => {
|
||||
setCrawlingProgress(35);
|
||||
setCrawlerLogs((prev) => [
|
||||
...prev,
|
||||
...selectedIds.map((id) => {
|
||||
const p = products.find((prod) => prod.item_id === id);
|
||||
return `[크롤링] '${p?.name || id}' 인터넷 최저가 비교 검색 수집 진행`;
|
||||
}),
|
||||
`[Search] 외부 커머스 유통 플랫폼(Coupang, Gmarket, Danawa) 지표 추출 시작...`,
|
||||
]);
|
||||
}, 500);
|
||||
|
||||
setTimeout(() => {
|
||||
setCrawlingProgress(72);
|
||||
setCrawlerLogs((prev) => [
|
||||
...prev,
|
||||
`[OCR] 수집 완료된 실시간 HTML/DOM 가격 노드 데이터 분석 중...`,
|
||||
`[Sync] 정제 단가 적용 (부가세 보정 및 할인 쿠폰 혜택가 산정)`,
|
||||
]);
|
||||
}, 1100);
|
||||
|
||||
setTimeout(() => {
|
||||
setCrawlingProgress(100);
|
||||
// NOTE: 인터넷 최저가 동기화는 전용 엔드포인트 연동 예정. 현재는 진행 애니메이션만 데모(서버 미반영).
|
||||
showToast(`선택한 ${selectedIds.length}개 상품의 인터넷 최저가 동기화는 준비 중입니다(데모).`, 'info');
|
||||
onDone();
|
||||
setIsCrawling(false);
|
||||
onClose();
|
||||
setCrawlingProgress(0);
|
||||
setCrawlerLogs([]);
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 backdrop-blur-xs">
|
||||
<div className="w-full max-w-lg bg-card border border-border rounded-lg shadow-2xl p-6 overflow-hidden animate-scale-up font-mono text-xs">
|
||||
|
||||
{/* Modal Title */}
|
||||
<div className="flex items-center justify-between pb-4 border-b border-border">
|
||||
<div className="flex items-center gap-2 text-foreground">
|
||||
<Globe className="text-rose-500 animate-pulse" size={18} />
|
||||
<Typography variant="h3">인터넷 최저가 API 실시간 수집 및 동기화</Typography>
|
||||
</div>
|
||||
{!isCrawling && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal Body */}
|
||||
<div className="my-6 space-y-4">
|
||||
<div className="p-3 bg-rose-500/5 border border-rose-500/20 rounded-md">
|
||||
<Typography variant="small" className="text-[11.5px] leading-relaxed text-left flex items-start gap-2">
|
||||
<AlertCircle size={15} className="text-rose-500 shrink-0 mt-0.5" />
|
||||
<span>
|
||||
총 <span className="font-bold text-rose-600 dark:text-rose-400 underline decoration-rose-500/50 decoration-2">{selectedIds.length}개</span> 품목에 대하여 네이버 오픈마켓, 다나와, 쿠팡 및 B2B 공공 유통망의 최저가 데이터를 수집 및 비교 분석하여 최신 최저가(minPrice) 필드로 다이렉트 동기화합니다.
|
||||
</span>
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
{/* Targeted Items List */}
|
||||
<div className="border border-border rounded p-2.5 bg-muted/20 space-y-1.5">
|
||||
<span className="text-[10px] text-muted-foreground font-bold block">수집 대상 상품 ({selectedIds.length})</span>
|
||||
<div className="max-h-24 overflow-y-auto space-y-1 pr-1">
|
||||
{selectedIds.map((id) => {
|
||||
const prod = products.find((p) => p.item_id === id);
|
||||
return prod ? (
|
||||
<div key={id} className="flex justify-between items-center text-[11px] py-1 border-b border-border/30 last:border-b-0">
|
||||
<span className="text-foreground truncate max-w-[200px] font-semibold">{prod.name}</span>
|
||||
<div className="flex items-center gap-1.5 font-mono">
|
||||
<span className="text-muted-foreground">{(prod.price ?? 0).toLocaleString()}원</span>
|
||||
<span className="text-muted-foreground">→</span>
|
||||
<span className="text-rose-500 font-bold">자동 가공 수집</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Crawling Progress View */}
|
||||
{isCrawling ? (
|
||||
<div className="space-y-3 pt-2">
|
||||
<div className="flex justify-between text-[11px] text-muted-foreground">
|
||||
<span className="flex items-center gap-1.5 font-bold text-foreground">
|
||||
<Loader2 size={13} className="animate-spin text-rose-500" />
|
||||
실시간 크롤링 엔진 데이터 동기화 동작 중...
|
||||
</span>
|
||||
<span className="font-bold text-rose-500">{crawlingProgress}%</span>
|
||||
</div>
|
||||
|
||||
{/* Progress Bar Container */}
|
||||
<div className="w-full bg-muted rounded-full h-2.5 overflow-hidden border border-border">
|
||||
<div
|
||||
className="bg-gradient-to-r from-rose-500 to-rose-600 h-full transition-all duration-300 rounded-full"
|
||||
style={{ width: `${crawlingProgress}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Terminal Log Output */}
|
||||
<div className="bg-zinc-950 dark:bg-black text-rose-300 p-3 rounded font-mono text-[10px] border border-zinc-800 space-y-1.5 max-h-36 overflow-y-auto shadow-inner">
|
||||
{crawlerLogs.map((log, idx) => (
|
||||
<div key={idx} className="flex items-start gap-1">
|
||||
<span className="text-zinc-600 select-none shrink-0">></span>
|
||||
<span className={`text-left break-all ${log.includes('[System]') ? 'text-zinc-400 font-bold' : log.includes('[OCR]') ? 'text-blue-400' : 'text-emerald-400'}`}>
|
||||
{log}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-4 border border-dashed border-border rounded bg-muted/10 space-y-2">
|
||||
<Cpu size={24} className="mx-auto text-muted-foreground/60" />
|
||||
<Typography variant="muted" className="text-[11px]">
|
||||
"최저가 업데이트 시작" 버튼을 누르시면 실시간 스크래핑 엔진이 시작됩니다.
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal Footer */}
|
||||
<div className="flex justify-end gap-2 pt-4 border-t border-border">
|
||||
<Button type="button" variant="outline" size="sm" disabled={isCrawling} onClick={onClose}>
|
||||
닫기
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" size="sm" disabled={isCrawling} onClick={handleStartCrawling}>
|
||||
{isCrawling ? (
|
||||
<>
|
||||
<RefreshCw className="animate-spin" />
|
||||
실시간 수집 분석중...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Globe />
|
||||
인터넷 최저가 가동
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import type { ItemCreate } from '@/api/generated/model/itemCreate';
|
||||
import type { ItemUpdate } from '@/api/generated/model/itemUpdate';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import ImageDropzone from '@/components/ImageDropzone';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Sheet } from '@/components/ui/sheet';
|
||||
import { type Product, categoriesList, toMinPrice } from '../types';
|
||||
|
||||
// 폼 검증 스키마. 필수: 상품명/상품코드/단가/최저가. 나머지는 선택.
|
||||
const schema = z.object({
|
||||
name: z.string().trim().min(1, '상품명을 작성하여 주십시오.'),
|
||||
code: z.string().trim().min(1, '상품코드를 입력해 주십시오.'),
|
||||
category: z.string(),
|
||||
price: z.number({ message: '숫자를 입력해 주십시오.' }).min(0, '단가는 0 이상이어야 합니다.'),
|
||||
minPrice: z.number({ message: '숫자를 입력해 주십시오.' }).min(0, '최저가는 0 이상이어야 합니다.'),
|
||||
modelName: z.string(),
|
||||
specification: z.string(),
|
||||
manufacturer: z.string(),
|
||||
origin: z.string(),
|
||||
unit: z.string(),
|
||||
shippingType: z.string(),
|
||||
imageUrl: z.string(),
|
||||
moq: z.string(),
|
||||
leadTime: z.number({ message: '숫자를 입력해 주십시오.' }).min(0),
|
||||
vatYn: z.boolean(),
|
||||
deliveryFeeYn: z.boolean(),
|
||||
internetLowestPriceYn: z.boolean(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
type ProductFormSheetProps = {
|
||||
open: boolean;
|
||||
mode: 'create' | 'edit';
|
||||
product: Product | null; // edit 모드일 때 초기값 출처
|
||||
onCreate: (data: ItemCreate) => Promise<void>;
|
||||
onUpdate: (itemId: string, data: ItemUpdate) => Promise<void>;
|
||||
onDelete: (itemId: string, name: string) => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
// mode/product로 폼 초기값 산출. create는 기본값, edit는 product에서.
|
||||
function buildDefaults(mode: 'create' | 'edit', product: Product | null): FormValues {
|
||||
if (mode === 'edit' && product) {
|
||||
return {
|
||||
name: product.name ?? '',
|
||||
code: product.code || '',
|
||||
category: product.category || '에너지/배터리',
|
||||
price: product.price || 0,
|
||||
minPrice: toMinPrice(product.price),
|
||||
modelName: product.model_name || '',
|
||||
specification: product.spec || '',
|
||||
manufacturer: product.manufacturer || '',
|
||||
origin: product.made_in || '',
|
||||
unit: product.quantity_unit || 'EA',
|
||||
shippingType: product.delivery_type || '벌크 물류 배송',
|
||||
imageUrl: product.image_url || '',
|
||||
moq: product.moq || '10 EA',
|
||||
leadTime: product.lead_time || 14,
|
||||
vatYn: product.vat_yn !== false,
|
||||
deliveryFeeYn: product.delivery_fee_yn || false,
|
||||
internetLowestPriceYn: product.internet_lowest_price_yn || false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: '',
|
||||
code: `PROD-BAT-${Math.floor(100 + Math.random() * 900)}`,
|
||||
category: '에너지/배터리',
|
||||
price: 1000000,
|
||||
minPrice: 800000,
|
||||
modelName: '',
|
||||
specification: '',
|
||||
manufacturer: '',
|
||||
origin: '대한민국',
|
||||
unit: 'EA',
|
||||
shippingType: '벌크 물류 배송',
|
||||
imageUrl: '',
|
||||
moq: '10 EA',
|
||||
leadTime: 14,
|
||||
vatYn: true,
|
||||
deliveryFeeYn: false,
|
||||
internetLowestPriceYn: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Input(디자인시스템)가 대부분 스타일을 갖고 있으므로 폼 고유 스펙만 남김
|
||||
const inputClass = 'text-foreground text-xs';
|
||||
|
||||
// 신규 등록 / 수정용 우측 드로어 폼. react-hook-form + zod로 검증.
|
||||
// 페이지는 key={mode + product?.item_id}로 리마운트시켜 초기값을 주입한다.
|
||||
export function ProductFormSheet({
|
||||
open,
|
||||
mode,
|
||||
product,
|
||||
onCreate,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
onClose,
|
||||
}: ProductFormSheetProps) {
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: buildDefaults(mode, product),
|
||||
});
|
||||
|
||||
// minPrice는 화면 전용(서버 미전송). 검증된 값만 payload로.
|
||||
const onValid = async (v: FormValues) => {
|
||||
const common = {
|
||||
name: v.name,
|
||||
code: v.code,
|
||||
category: v.category,
|
||||
price: v.price,
|
||||
model_name: v.modelName,
|
||||
spec: v.specification,
|
||||
manufacturer: v.manufacturer,
|
||||
made_in: v.origin,
|
||||
quantity_unit: v.unit,
|
||||
delivery_type: v.shippingType,
|
||||
moq: v.moq,
|
||||
lead_time: v.leadTime,
|
||||
vat_yn: v.vatYn,
|
||||
delivery_fee_yn: v.deliveryFeeYn,
|
||||
internet_lowest_price_yn: v.internetLowestPriceYn,
|
||||
};
|
||||
|
||||
if (mode === 'create') {
|
||||
const payload: ItemCreate = {
|
||||
...common,
|
||||
image_url: v.imageUrl || 'https://images.unsplash.com/photo-1593941707882-a5bba14938c7?w=300',
|
||||
};
|
||||
try {
|
||||
await onCreate(payload);
|
||||
showToast('신규 B2B 상품이 안전하게 등록되었습니다.', 'success');
|
||||
onClose();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '상품 등록 실패', 'error');
|
||||
}
|
||||
} else if (product) {
|
||||
const payload: ItemUpdate = { ...common, image_url: v.imageUrl || undefined };
|
||||
try {
|
||||
await onUpdate(product.item_id, payload);
|
||||
showToast('상품 정보가 성공적으로 수정되었습니다.', 'success');
|
||||
onClose();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '상품 수정 실패', 'error');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={open}
|
||||
title={mode === 'create' ? '신규 상품 등록' : '상품 정보 수정'}
|
||||
onClose={onClose}
|
||||
>
|
||||
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
|
||||
{/* Product Name */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">상품명</Typography>
|
||||
<Input
|
||||
id="form-product-name"
|
||||
type="text"
|
||||
{...register('name')}
|
||||
className={inputClass}
|
||||
placeholder="예: B2B 고용량 배터리 팩..."
|
||||
/>
|
||||
{errors.name && <p className="text-[10px] text-rose-500">{errors.name.message}</p>}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Code */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">상품코드</Typography>
|
||||
<Input
|
||||
id="form-product-code"
|
||||
type="text"
|
||||
{...register('code')}
|
||||
className={inputClass}
|
||||
placeholder="PROD-XXX"
|
||||
/>
|
||||
{errors.code && <p className="text-[10px] text-rose-500">{errors.code.message}</p>}
|
||||
</div>
|
||||
{/* Category */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">분류 카테고리</Typography>
|
||||
<select
|
||||
id="form-product-category"
|
||||
{...register('category')}
|
||||
className={`${inputClass} cursor-pointer`}
|
||||
>
|
||||
{categoriesList.filter((c) => c !== 'ALL').map((c) => (
|
||||
<option key={c} value={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Price */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">상품 단가 (₩)</Typography>
|
||||
<Input
|
||||
id="form-product-price"
|
||||
type="number"
|
||||
{...register('price', { valueAsNumber: true })}
|
||||
className={`${inputClass} font-mono`}
|
||||
placeholder="0"
|
||||
/>
|
||||
{errors.price && <p className="text-[10px] text-rose-500">{errors.price.message}</p>}
|
||||
</div>
|
||||
{/* Min Price */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label" className="text-rose-500">인터넷 최저가 (₩)</Typography>
|
||||
<Input
|
||||
id="form-product-minprice"
|
||||
type="number"
|
||||
{...register('minPrice', { valueAsNumber: true })}
|
||||
className={`${inputClass} font-mono font-bold text-rose-600 dark:text-rose-400`}
|
||||
placeholder="0"
|
||||
/>
|
||||
{errors.minPrice && <p className="text-[10px] text-rose-500">{errors.minPrice.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Model Name */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">모델명</Typography>
|
||||
<Input
|
||||
id="form-product-model"
|
||||
type="text"
|
||||
{...register('modelName')}
|
||||
placeholder="예: XL-V80"
|
||||
/>
|
||||
</div>
|
||||
{/* Unit */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">취급 단위</Typography>
|
||||
<Input
|
||||
type="text"
|
||||
{...register('unit')}
|
||||
placeholder="예: EA, BOX, SET, ROLL..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Specification */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">상품 규격</Typography>
|
||||
<textarea
|
||||
{...register('specification')}
|
||||
rows={2}
|
||||
className="w-full p-2 bg-background border border-border rounded text-xs resize-none"
|
||||
placeholder="예: 최대 인장력, 탑재 부피 사양 전압 규격..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* MOQ */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">최소 주문 수량</Typography>
|
||||
<Input
|
||||
type="text"
|
||||
{...register('moq')}
|
||||
placeholder="예: 10 EA, 1 BOX"
|
||||
/>
|
||||
</div>
|
||||
{/* Lead Time */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">배송 리드타임 (일)</Typography>
|
||||
<Input
|
||||
type="number"
|
||||
{...register('leadTime', { valueAsNumber: true })}
|
||||
className="font-mono"
|
||||
placeholder="14"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Manufacturer */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">제조사</Typography>
|
||||
<Input
|
||||
type="text"
|
||||
{...register('manufacturer')}
|
||||
placeholder="제조사명"
|
||||
/>
|
||||
</div>
|
||||
{/* Origin */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">제조 국가</Typography>
|
||||
<Input
|
||||
type="text"
|
||||
{...register('origin')}
|
||||
placeholder="예: 대한민국, 독일"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Shipping Type */}
|
||||
<div className="space-y-1">
|
||||
<Typography as="label" variant="label">배송 형태</Typography>
|
||||
<Input
|
||||
type="text"
|
||||
{...register('shippingType')}
|
||||
placeholder="예: 벌크 물류 배송, 특수 안전 수송..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* DB Schema Booleans (vat_yn, delivery_fee_yn) using Switches */}
|
||||
<div className="p-3 bg-muted/35 border border-border/80 rounded-md space-y-3">
|
||||
<span className="text-[10px] uppercase tracking-wider font-bold text-muted-foreground block">부가 정보 설정</span>
|
||||
|
||||
<Controller
|
||||
control={control}
|
||||
name="vatYn"
|
||||
render={({ field }) => (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-semibold text-foreground">VAT 포함 여부:</span>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={field.value}
|
||||
onClick={() => field.onChange(!field.value)}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-all duration-200 focus:outline-none ${
|
||||
field.value ? 'bg-indigo-600 dark:bg-indigo-500' : 'bg-zinc-300 dark:bg-zinc-700'
|
||||
}`}
|
||||
>
|
||||
<span className={`pointer-events-none block h-4 w-4 rounded-full bg-white shadow transition-all duration-200 ${
|
||||
field.value ? 'translate-x-4' : 'translate-x-0'
|
||||
}`} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Controller
|
||||
control={control}
|
||||
name="deliveryFeeYn"
|
||||
render={({ field }) => (
|
||||
<div className="flex items-center justify-between border-t border-border/40 pt-2.5">
|
||||
<span className="font-semibold text-foreground">배송비 포함 여부:</span>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={field.value}
|
||||
onClick={() => field.onChange(!field.value)}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-all duration-200 focus:outline-none ${
|
||||
field.value ? 'bg-indigo-600 dark:bg-indigo-500' : 'bg-zinc-300 dark:bg-zinc-700'
|
||||
}`}
|
||||
>
|
||||
<span className={`pointer-events-none block h-4 w-4 rounded-full bg-white shadow transition-all duration-200 ${
|
||||
field.value ? 'translate-x-4' : 'translate-x-0'
|
||||
}`} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Drag-and-Drop Image Dropzone */}
|
||||
<Controller
|
||||
control={control}
|
||||
name="imageUrl"
|
||||
render={({ field }) => (
|
||||
<ImageDropzone
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onClear={() => field.onChange('')}
|
||||
label="대표이미지 URL"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Buttons wrapper */}
|
||||
<div className="pt-4 flex items-center gap-2 border-t border-border mt-8 justify-between z-10">
|
||||
{mode === 'edit' && product && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onDelete(product.item_id, product.name);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
삭제
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex items-center gap-2 flex-1 justify-end">
|
||||
<Button type="button" variant="outline" size="sm" onClick={onClose}>
|
||||
취소
|
||||
</Button>
|
||||
<Button type="submit" size="sm" disabled={isSubmitting}>
|
||||
{mode === 'create' ? '신규 상품 발행' : '변경사항 저장'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Image as ImageIcon } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { DataTable } from '@/components/ui/data-table';
|
||||
import { TablePagination } from '@/components/ui/table-pagination';
|
||||
import { type Product, toMinPrice } from '../types';
|
||||
|
||||
type ProductTableProps = {
|
||||
data: Product[];
|
||||
selectedIds: string[];
|
||||
onSelectionChange: (ids: string[]) => void;
|
||||
onRowClick: (prod: Product) => void;
|
||||
page: number;
|
||||
totalPages: number;
|
||||
totalCount: number;
|
||||
pageSize: number;
|
||||
onPageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
export function ProductTable({
|
||||
data,
|
||||
selectedIds,
|
||||
onSelectionChange,
|
||||
onRowClick,
|
||||
page,
|
||||
totalPages,
|
||||
totalCount,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
}: ProductTableProps) {
|
||||
return (
|
||||
<DataTable
|
||||
data={data}
|
||||
rowKey={(prod) => prod.item_id}
|
||||
onRowClick={onRowClick}
|
||||
selection={{ selectedKeys: selectedIds, onSelectionChange }}
|
||||
empty="부합하는 B2B 상품 데이터 정보가 식별되지 않습니다."
|
||||
footer={
|
||||
<TablePagination
|
||||
page={page}
|
||||
totalPages={totalPages}
|
||||
totalCount={totalCount}
|
||||
pageSize={pageSize}
|
||||
onPageChange={onPageChange}
|
||||
label="검색 결과"
|
||||
unit="건"
|
||||
/>
|
||||
}
|
||||
columns={[
|
||||
{
|
||||
header: '상품명',
|
||||
align: 'left',
|
||||
headClassName: 'w-2/5',
|
||||
cell: (prod) => (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-10 w-10 flex-shrink-0 rounded border border-border overflow-hidden bg-muted flex items-center justify-center">
|
||||
{prod.image_url ? (
|
||||
<img src={prod.image_url} alt={prod.name} className="h-full w-full object-cover" referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
<ImageIcon size={18} className="text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-semibold text-foreground text-sm line-clamp-1">{prod.name}</div>
|
||||
{prod.model_name && <span className="text-[10px] text-muted-foreground font-mono">{prod.model_name}</span>}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '상품코드',
|
||||
align: 'left',
|
||||
cellClassName: 'font-mono font-medium text-muted-foreground',
|
||||
cell: (prod) => prod.code,
|
||||
},
|
||||
{
|
||||
header: '카테고리',
|
||||
align: 'left',
|
||||
cell: (prod) => (
|
||||
<Badge variant="outline" className="text-[10.5px] border-border text-foreground font-medium bg-muted py-0.5 px-1.5 rounded-full">
|
||||
{prod.category}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '상품 단가',
|
||||
align: 'right',
|
||||
cellClassName: 'font-mono font-bold text-foreground',
|
||||
cell: (prod) => `₩${(prod.price || 0).toLocaleString()}`,
|
||||
},
|
||||
{
|
||||
header: '인터넷 최저가',
|
||||
align: 'right',
|
||||
cellClassName: 'font-mono font-semibold text-rose-600 dark:text-rose-400',
|
||||
cell: (prod) => `₩${(prod.minPrice || toMinPrice(prod.price)).toLocaleString()}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useState } from 'react';
|
||||
import type { Product } from '../types';
|
||||
|
||||
const ITEMS_PER_PAGE = 5;
|
||||
|
||||
// 상품 목록에 대한 검색/카테고리/페이지네이션 UI state + 파생 결과.
|
||||
// 검색·카테고리 변경 시 1페이지로 리셋한다.
|
||||
export function useProductFilters(products: Product[]) {
|
||||
const [search, setSearchRaw] = useState('');
|
||||
const [categoryFilter, setCategoryFilterRaw] = useState('ALL');
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const setSearch = (v: string) => {
|
||||
setSearchRaw(v);
|
||||
setPage(1);
|
||||
};
|
||||
const setCategoryFilter = (v: string) => {
|
||||
setCategoryFilterRaw(v);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const filtered = products.filter((prod) => {
|
||||
if (prod.deleted) return false; // soft-deleted 제외
|
||||
const q = search.toLowerCase();
|
||||
const matchesSearch =
|
||||
(prod.name ?? '').toLowerCase().includes(q) ||
|
||||
(prod.code ? prod.code.toLowerCase().includes(q) : false);
|
||||
const matchesCategory = categoryFilter === 'ALL' || prod.category === categoryFilter;
|
||||
return matchesSearch && matchesCategory;
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(filtered.length / ITEMS_PER_PAGE) || 1;
|
||||
const paginated = filtered.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
|
||||
|
||||
return {
|
||||
search,
|
||||
setSearch,
|
||||
categoryFilter,
|
||||
setCategoryFilter,
|
||||
page,
|
||||
setPage,
|
||||
paginated,
|
||||
totalPages,
|
||||
totalCount: filtered.length,
|
||||
itemsPerPage: ITEMS_PER_PAGE,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
useListItems,
|
||||
createItem,
|
||||
updateItem,
|
||||
deleteItem,
|
||||
getListItemsQueryKey,
|
||||
} from '@/api/generated/item/item';
|
||||
import type { ItemResponse } from '@/api/generated/model/itemResponse';
|
||||
import type { ItemCreate } from '@/api/generated/model/itemCreate';
|
||||
import type { ItemUpdate } from '@/api/generated/model/itemUpdate';
|
||||
import { type Product, toMinPrice } from '../types';
|
||||
|
||||
const LIST_PARAMS = { size: 100 };
|
||||
|
||||
// 상품 서버 데이터 + CRUD. orval 뮤테이션 호출 후 목록 쿼리 무효화(재조회).
|
||||
// 실패 시 throw → 호출부에서 toast 처리.
|
||||
export function useProducts() {
|
||||
const queryClient = useQueryClient();
|
||||
const itemsQuery = useListItems(LIST_PARAMS);
|
||||
|
||||
const refresh = () =>
|
||||
queryClient.invalidateQueries({ queryKey: getListItemsQueryKey(LIST_PARAMS) });
|
||||
|
||||
const createProduct = async (data: ItemCreate) => {
|
||||
await createItem(data);
|
||||
await refresh();
|
||||
};
|
||||
const updateProduct = async (itemId: string, data: ItemUpdate) => {
|
||||
await updateItem(itemId, data);
|
||||
await refresh();
|
||||
};
|
||||
const deleteProduct = async (itemId: string) => {
|
||||
await deleteItem(itemId);
|
||||
await refresh();
|
||||
};
|
||||
// 엑셀 일괄 등록 — 검증된 행들을 순차 생성 후 한 번만 재조회.
|
||||
const bulkCreate = async (rows: ItemCreate[]) => {
|
||||
for (const row of rows) {
|
||||
await createItem(row);
|
||||
}
|
||||
await refresh();
|
||||
};
|
||||
|
||||
// 서버 ItemResponse → UI Product (화면 전용 파생 필드 부여)
|
||||
const items =
|
||||
(itemsQuery.data as { data?: { data?: { items?: ItemResponse[] } } } | undefined)
|
||||
?.data?.data?.items ?? [];
|
||||
const products: Product[] = items.map((it) => ({
|
||||
...it,
|
||||
id: it.item_id,
|
||||
minPrice: toMinPrice(it.price),
|
||||
status: 'ACTIVE',
|
||||
}));
|
||||
|
||||
return { products, createProduct, updateProduct, deleteProduct, bulkCreate, refresh, itemsQuery };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ItemResponse } from '@/api/generated/model/itemResponse';
|
||||
|
||||
// UI에서 쓰는 상품 타입. 서버 ItemResponse에 화면 전용 파생 필드를 얹는다.
|
||||
export type Product = ItemResponse & {
|
||||
deleted?: boolean;
|
||||
id?: string;
|
||||
minPrice?: number;
|
||||
status?: string;
|
||||
};
|
||||
|
||||
// 분류 카테고리. 'ALL'은 필터 전용(폼에서는 제외).
|
||||
export const categoriesList = ['ALL', '에너지/배터리', '자동화설비', '반도체소자/센서', '신소재', '광학/통신'];
|
||||
|
||||
// 인터넷 최저가 데모 산정(표준 단가의 83%). 서버 미연동 — 표시/초기값 용도.
|
||||
export const toMinPrice = (price?: number | null) => Math.round((price || 0) * 0.83);
|
||||
@@ -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 ? '와일드 카드' : '협상 카드',
|
||||
};
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user