[feat] negodata/front: 협상대화 카드내용 렌더 + 견적상세 헤더·테이블 UI 정리
- 협상대화: 사용 카드 번호/멘트(Slate 서식본)/와일드 조건·메모 표시, SlateRenderer
밑줄·헥스색·{변수} 치환 보정, 말풍선 우측정렬·발신자 아바타 제거
- 견적상세 헤더: DB 컬럼명 라벨 제거, 견적정보/(진행상태+세팅)/상품(이미지) 2열 재배치,
협상카드 탭에 사용 카드 수 표시
- DataTable 행 패딩 축소, 협력사명 아바타 제거, 카드관리 본인 카드 안내문
- orval 재생성(QuotationCardData 신규 필드)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
df68609c49
commit
7186446068
114 files changed
+4731
-5537
No files matched your search
@@ -1,317 +0,0 @@
|
||||
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
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) => Promise<void>;
|
||||
onUpdate: (id: string, input: CardInput) => Promise<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 = async (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,
|
||||
};
|
||||
const kind = v.isWildcard ? '와일드카드' : '협상카드';
|
||||
try {
|
||||
if (mode === 'create') {
|
||||
await onCreate(input);
|
||||
showToast(`${kind}가 추가되었습니다.`, 'success');
|
||||
} else if (card) {
|
||||
await onUpdate(card.id, input);
|
||||
showToast('정보가 수정되었습니다.', 'success');
|
||||
}
|
||||
onClose();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : `${kind} 저장 실패`, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
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
|
||||
value={field.value ? 'WILD' : 'CARD'}
|
||||
onValueChange={(v) => {
|
||||
// 카드 종류는 등록 시에만 정한다(수정 시 테이블 이동 불가 → 고정).
|
||||
if (mode !== 'create') return;
|
||||
const wild = v === 'WILD';
|
||||
field.onChange(wild);
|
||||
setValue('code', generateCardCode(wild));
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="form-card-is-wildcard" className="w-full" disabled={mode === 'edit'}>
|
||||
<SelectValue>
|
||||
{(value) => (value === 'WILD' ? '와일드카드' : '일반 협상카드')}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="CARD">일반 협상카드</SelectItem>
|
||||
<SelectItem value="WILD">와일드카드</SelectItem>
|
||||
</SelectContent>
|
||||
</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,311 @@
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import type { Descendant } from 'slate';
|
||||
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { type NegotiationCard, type CardTab, generateCardCode } from '../types';
|
||||
import type { CardInput } from '../hooks/useCards';
|
||||
import { CardScriptEditor, deserialize, serializeToText } from '../editor';
|
||||
|
||||
const schema = z.object({
|
||||
isWildcard: z.boolean(),
|
||||
code: z.string().trim().min(1, '카드번호는 필수 기입 사항입니다.'),
|
||||
title: z.string().trim().min(1, '카드이름은 필수 기입 사항입니다.'),
|
||||
editorScript: z
|
||||
.custom<Descendant[]>((v) => Array.isArray(v))
|
||||
.refine((v) => serializeToText(v).trim().length > 0, '스크립트를 작성해 주십시오.'),
|
||||
status: z.enum(['ACTIVE', 'INACTIVE']),
|
||||
triggerCondition: z.string(),
|
||||
memo: z.string(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
type CardFormSheetProps = {
|
||||
open: boolean;
|
||||
mode: 'create' | 'edit';
|
||||
card: NegotiationCard | null; // edit 모드 초기값 출처
|
||||
activeTab: CardTab; // create 시 기본 카드 종류 결정
|
||||
onCreate: (input: CardInput) => Promise<void>;
|
||||
onUpdate: (id: string, input: CardInput) => Promise<void>;
|
||||
onDelete: (id: string, title: string) => 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,
|
||||
// 저장된 Slate JSON 우선, 없으면 레거시 평문 script 를 변수 노드로 복원.
|
||||
editorScript: deserialize(card.editorScript, card.scriptPreview),
|
||||
status: card.status,
|
||||
triggerCondition: card.triggerCondition || '',
|
||||
memo: card.memo || '',
|
||||
};
|
||||
}
|
||||
const wild = activeTab === 'WILD';
|
||||
return {
|
||||
isWildcard: wild,
|
||||
code: generateCardCode(wild),
|
||||
title: '',
|
||||
editorScript: deserialize(), // 새 빈 값(공용 상수 mutate 방지)
|
||||
status: 'ACTIVE',
|
||||
triggerCondition: '',
|
||||
memo: '',
|
||||
};
|
||||
}
|
||||
|
||||
// 협상카드/와일드카드 등록·수정 우측 드로어 폼. react-hook-form + zod로 검증.
|
||||
// 상품·협력사 폼과 동일하게 공통 Sheet 셸을 쓴다(우측 슬라이드).
|
||||
// 페이지는 key={mode + card?.id}로 리마운트시켜 초기값을 주입한다.
|
||||
export function CardFormSheet({
|
||||
open,
|
||||
mode,
|
||||
card,
|
||||
activeTab,
|
||||
onCreate,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
onClose,
|
||||
}: CardFormSheetProps) {
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: buildDefaults(mode, card, activeTab),
|
||||
});
|
||||
|
||||
const isWildcard = watch('isWildcard');
|
||||
|
||||
const onValid = async (v: FormValues) => {
|
||||
const input: CardInput = {
|
||||
title: v.title,
|
||||
code: v.code,
|
||||
editorScript: v.editorScript,
|
||||
status: v.status,
|
||||
isWildcard: v.isWildcard,
|
||||
triggerCondition: v.triggerCondition,
|
||||
memo: v.memo,
|
||||
};
|
||||
const kind = v.isWildcard ? '와일드카드' : '협상카드';
|
||||
try {
|
||||
if (mode === 'create') {
|
||||
await onCreate(input);
|
||||
showToast(`${kind}가 추가되었습니다.`, 'success');
|
||||
} else if (card) {
|
||||
await onUpdate(card.id, input);
|
||||
showToast('정보가 수정되었습니다.', 'success');
|
||||
}
|
||||
onClose();
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : `${kind} 저장 실패`, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const title =
|
||||
mode === 'create'
|
||||
? isWildcard
|
||||
? '신규 와일드카드 등록'
|
||||
: '신규 협상카드 등록'
|
||||
: isWildcard
|
||||
? '와일드카드 정보 수정'
|
||||
: '협상카드 정보 수정';
|
||||
|
||||
return (
|
||||
<Sheet open={open} title={title} onClose={onClose}>
|
||||
<form onSubmit={handleSubmit(onValid)} className="mt-6 space-y-4 text-xs font-mono">
|
||||
<div className="grid grid-cols-1 sm: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
|
||||
value={field.value ? 'WILD' : 'CARD'}
|
||||
onValueChange={(v) => {
|
||||
// 카드 종류는 등록 시에만 정한다(수정 시 테이블 이동 불가 → 고정).
|
||||
if (mode !== 'create') return;
|
||||
const wild = v === 'WILD';
|
||||
field.onChange(wild);
|
||||
setValue('code', generateCardCode(wild));
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="form-card-is-wildcard" className="w-full" disabled={mode === 'edit'}>
|
||||
<SelectValue>
|
||||
{(value) => (value === 'WILD' ? '와일드카드' : '일반 협상카드')}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="CARD">일반 협상카드</SelectItem>
|
||||
<SelectItem value="WILD">와일드카드</SelectItem>
|
||||
</SelectContent>
|
||||
</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">
|
||||
<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>
|
||||
<Controller
|
||||
control={control}
|
||||
name="editorScript"
|
||||
render={({ field }) => (
|
||||
<CardScriptEditor
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
placeholder="협상 중에 상대에게 발송할 멘트 스크립트를 기술하십시오. 굵게·색상·변수 칩을 활용하세요."
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{errors.editorScript && (
|
||||
<p className="text-[10px] text-rose-500">{errors.editorScript.message as string}</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 — 다른 폼 sheet와 동일: 좌측 삭제(edit), 우측 취소/저장 */}
|
||||
<div className="pt-4 flex items-center justify-between gap-2 border-t border-border mt-8">
|
||||
{mode === 'edit' && card && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onDelete(card.id, card.title);
|
||||
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" id="form-card-submit" size="sm" disabled={isSubmitting}>
|
||||
{mode === 'create' ? '저장' : '수정'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
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) {
|
||||
export function CardTable({ data, onEdit }: CardTableProps) {
|
||||
return (
|
||||
<DataTable
|
||||
data={data}
|
||||
@@ -39,6 +37,7 @@ export function CardTable({ data, onEdit, onDelete }: CardTableProps) {
|
||||
{
|
||||
header: '카드이름',
|
||||
headClassName: 'w-52',
|
||||
mobileHeader: true, // 모바일 카드뷰 제목(첫 컬럼 '구분' 배지 대신)
|
||||
cell: (card) => (
|
||||
<>
|
||||
<div className="font-semibold text-foreground text-sm">{card.title}</div>
|
||||
@@ -53,8 +52,9 @@ export function CardTable({ data, onEdit, onDelete }: CardTableProps) {
|
||||
{
|
||||
header: '스크립트',
|
||||
cellClassName: 'font-mono text-muted-foreground',
|
||||
mobileBlock: true, // 긴 미리보기 블록 → 모바일 카드뷰에서 라벨 아래 풀폭
|
||||
cell: (card) => (
|
||||
<div className="line-clamp-2 bg-muted/20 p-2.5 rounded border border-border/30 text-[11px] leading-relaxed">
|
||||
<div className="line-clamp-1 bg-muted/20 px-2 py-1 rounded border border-border/30 text-[11px] leading-snug">
|
||||
{card.scriptPreview}
|
||||
</div>
|
||||
),
|
||||
@@ -84,35 +84,6 @@ export function CardTable({ data, onEdit, onDelete }: CardTableProps) {
|
||||
<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,82 @@
|
||||
import { useCallback } from 'react';
|
||||
import { Slate, Editable } from 'slate-react';
|
||||
import type { RenderElementProps, RenderLeafProps } from 'slate-react';
|
||||
import type { Descendant } from 'slate';
|
||||
import { useCardScriptEditor } from './useCardScriptEditor';
|
||||
import { CardScriptToolbar } from './CardScriptToolbar';
|
||||
import { variableLabel } from './variables';
|
||||
|
||||
type CardScriptEditorProps = {
|
||||
value: Descendant[]; // 마운트 시 초기값(폼 리마운트로 갱신)
|
||||
onChange: (value: Descendant[]) => void;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
};
|
||||
|
||||
// 협상카드 스크립트 리치텍스트 에디터. 굵게/밑줄/색상 마크 + {변수} 칩 지원.
|
||||
// 값(Slate JSON)은 폼이 들고, 평문(script) 직렬화는 저장 시 serializeToText 로 파생한다.
|
||||
export function CardScriptEditor({ value, onChange, disabled, placeholder }: CardScriptEditorProps) {
|
||||
const editor = useCardScriptEditor();
|
||||
|
||||
const renderElement = useCallback((props: RenderElementProps) => <Element {...props} />, []);
|
||||
const renderLeaf = useCallback((props: RenderLeafProps) => <Leaf {...props} />, []);
|
||||
|
||||
// 선택(set_selection)만 바뀐 경우는 폼 상태를 건드리지 않는다(불필요한 dirty/검증 방지).
|
||||
const handleChange = (next: Descendant[]) => {
|
||||
const contentChanged = editor.operations.some((op) => op.type !== 'set_selection');
|
||||
if (contentChanged) onChange(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border border-border rounded-md overflow-hidden bg-background focus-within:border-foreground/30 transition-all">
|
||||
<Slate editor={editor} initialValue={value} onChange={handleChange}>
|
||||
{!disabled && <CardScriptToolbar />}
|
||||
<Editable
|
||||
readOnly={disabled}
|
||||
spellCheck={false}
|
||||
renderElement={renderElement}
|
||||
renderLeaf={renderLeaf}
|
||||
placeholder={placeholder}
|
||||
className="min-h-[88px] w-full p-3 text-xs leading-relaxed font-sans focus:outline-none [&_[data-slate-placeholder]]:text-muted-foreground"
|
||||
/>
|
||||
</Slate>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Leaf({ attributes, children, leaf }: RenderLeafProps) {
|
||||
let node = children;
|
||||
if (leaf.bold) node = <strong>{node}</strong>;
|
||||
if (leaf.underline) node = <u>{node}</u>;
|
||||
return (
|
||||
<span {...attributes} style={leaf.color ? { color: leaf.color } : undefined}>
|
||||
{node}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// 인라인 void 옆에 커서를 못 두는 Chromium 버그 회피용 zero-width 스페이서(Slate 공식 패턴).
|
||||
const InlineChromiumBugfix = () => (
|
||||
<span contentEditable={false} style={{ fontSize: 0 }}>
|
||||
{String.fromCodePoint(160) /* nbsp */}
|
||||
</span>
|
||||
);
|
||||
|
||||
function Element(props: RenderElementProps) {
|
||||
const { attributes, children, element } = props;
|
||||
if (element.type === 'variable') {
|
||||
return (
|
||||
<span
|
||||
{...attributes}
|
||||
contentEditable={false}
|
||||
className="mx-0.5 rounded-md border border-amber-300/60 bg-amber-100/70 px-1.5 py-0.5 text-[11px] font-semibold text-amber-900 dark:border-amber-400/30 dark:bg-amber-400/15 dark:text-amber-200"
|
||||
>
|
||||
<InlineChromiumBugfix />
|
||||
{variableLabel(element.name)}
|
||||
{children}
|
||||
<InlineChromiumBugfix />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <p {...attributes}>{children}</p>;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { MouseEvent, ReactNode } from 'react';
|
||||
import { useSlate } from 'slate-react';
|
||||
import { Bold, Underline } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
activeColor,
|
||||
isMarkActive,
|
||||
insertVariable,
|
||||
setColor,
|
||||
toggleMark,
|
||||
type TextMark,
|
||||
} from './slate';
|
||||
import { CARD_VARIABLES } from './variables';
|
||||
|
||||
// 색상 프리셋 — 기본/강조(빨강)/보조(파랑).
|
||||
// negowiz 동일 프리셋: 검정 / 빨강 / 파랑.
|
||||
const COLORS: { value: string; label: string }[] = [
|
||||
{ value: '#151515', label: '검정' },
|
||||
{ value: '#ED2024', label: '빨강' },
|
||||
{ value: '#4880EF', label: '파랑' },
|
||||
];
|
||||
|
||||
// 툴바 버튼은 onMouseDown + preventDefault 로 에디터 선택/포커스를 유지해야 한다(클릭 시 blur 방지).
|
||||
function hold(handler: () => void) {
|
||||
return (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
handler();
|
||||
};
|
||||
}
|
||||
|
||||
export function CardScriptToolbar() {
|
||||
const editor = useSlate();
|
||||
const curColor = activeColor(editor);
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-1 bg-muted/45 px-2 py-1.5 border-b border-border select-none">
|
||||
<MarkButton mark="bold" active={isMarkActive(editor, 'bold')} onToggle={() => toggleMark(editor, 'bold')}>
|
||||
<Bold size={13} />
|
||||
</MarkButton>
|
||||
<MarkButton
|
||||
mark="underline"
|
||||
active={isMarkActive(editor, 'underline')}
|
||||
onToggle={() => toggleMark(editor, 'underline')}
|
||||
>
|
||||
<Underline size={13} />
|
||||
</MarkButton>
|
||||
|
||||
<Divider />
|
||||
|
||||
{COLORS.map((c) => (
|
||||
<button
|
||||
key={c.value}
|
||||
type="button"
|
||||
title={`색상: ${c.label}`}
|
||||
onMouseDown={hold(() => setColor(editor, c.value))}
|
||||
className={cn(
|
||||
'h-5 w-5 rounded-full border transition-all',
|
||||
curColor === c.value ? 'ring-2 ring-foreground/40 ring-offset-1' : 'border-border',
|
||||
)}
|
||||
style={{ backgroundColor: c.value }}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Divider />
|
||||
|
||||
<span className="text-[10px] text-muted-foreground mr-0.5">변수</span>
|
||||
{CARD_VARIABLES.map((v) => (
|
||||
<button
|
||||
key={v.name}
|
||||
type="button"
|
||||
title={`{${v.name}} 삽입`}
|
||||
onMouseDown={hold(() => insertVariable(editor, v.name))}
|
||||
className="px-1.5 py-0.5 rounded border border-border bg-background text-[10px] font-semibold text-foreground hover:bg-muted cursor-pointer"
|
||||
>
|
||||
{v.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MarkButton({
|
||||
mark,
|
||||
active,
|
||||
onToggle,
|
||||
children,
|
||||
}: {
|
||||
mark: TextMark;
|
||||
active: boolean;
|
||||
onToggle: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
title={mark === 'bold' ? '굵게' : '밑줄'}
|
||||
onMouseDown={hold(onToggle)}
|
||||
className={cn(
|
||||
'flex h-6 w-6 items-center justify-center rounded border transition-all cursor-pointer',
|
||||
active
|
||||
? 'bg-foreground text-background border-foreground'
|
||||
: 'bg-background text-foreground border-border hover:bg-muted',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const Divider = () => <span className="mx-1 h-4 w-px bg-border" />;
|
||||
@@ -0,0 +1,4 @@
|
||||
export { CardScriptEditor } from './CardScriptEditor';
|
||||
// deserialize() 는 항상 새 배열을 반환 → Slate initialValue 로 안전. 공용 mutable 상수는 export 하지 않는다.
|
||||
export { deserialize, serializeToText } from './slate';
|
||||
export { CARD_VARIABLES } from './variables';
|
||||
@@ -0,0 +1,144 @@
|
||||
import { createEditor, Editor, Element as SlateElement, Transforms } from 'slate';
|
||||
import type { BaseEditor, Descendant } from 'slate';
|
||||
import type { ReactEditor } from 'slate-react';
|
||||
import type { HistoryEditor } from 'slate-history';
|
||||
import { isKnownVariable } from './variables';
|
||||
|
||||
// ── 스키마 ────────────────────────────────────────────────
|
||||
// negowiz 는 곳곳에서 `as any` 로 노드 타입을 우회했지만, 여기선 Slate 의 CustomTypes
|
||||
// 모듈 보강으로 editor/element/text 를 정적 타입화한다(툴바·렌더·커맨드 전부 타입 안전).
|
||||
export type TextMark = 'bold' | 'underline';
|
||||
|
||||
export type CustomText = {
|
||||
text: string;
|
||||
bold?: boolean;
|
||||
underline?: boolean;
|
||||
color?: string; // 색상 코드(#RRGGBB)
|
||||
};
|
||||
|
||||
export type VariableElement = {
|
||||
type: 'variable';
|
||||
name: string; // CardVariable.name
|
||||
children: CustomText[]; // void 라 비어있음([{text:''}])
|
||||
};
|
||||
|
||||
export type ParagraphElement = {
|
||||
type: 'paragraph';
|
||||
children: (CustomText | VariableElement)[];
|
||||
};
|
||||
|
||||
export type CustomElement = ParagraphElement | VariableElement;
|
||||
|
||||
declare module 'slate' {
|
||||
interface CustomTypes {
|
||||
Editor: BaseEditor & ReactEditor & HistoryEditor;
|
||||
Element: CustomElement;
|
||||
Text: CustomText;
|
||||
}
|
||||
}
|
||||
|
||||
// 항상 새 배열을 만든다(Slate 가 initialValue 를 직접 mutate 하므로 공유 금지).
|
||||
const cloneEmpty = (): Descendant[] => [{ type: 'paragraph', children: [{ text: '' }] }];
|
||||
|
||||
// ── 플러그인 ──────────────────────────────────────────────
|
||||
// 변수 노드를 인라인 + void(내용 수정 불가) + markableVoid(마크는 허용)로 동작시킨다.
|
||||
export function withVariables<T extends Editor>(editor: T): T {
|
||||
const { isInline, isVoid, markableVoid } = editor;
|
||||
editor.isInline = (el) => el.type === 'variable' || isInline(el);
|
||||
editor.isVoid = (el) => el.type === 'variable' || isVoid(el);
|
||||
editor.markableVoid = (el) => el.type === 'variable' || markableVoid(el);
|
||||
return editor;
|
||||
}
|
||||
|
||||
export const createCardEditor = () => createEditor();
|
||||
|
||||
// ── 마크/색상/변수 커맨드 ──────────────────────────────────
|
||||
export function isMarkActive(editor: Editor, mark: TextMark): boolean {
|
||||
const marks = Editor.marks(editor);
|
||||
return marks ? marks[mark] === true : false;
|
||||
}
|
||||
|
||||
export function toggleMark(editor: Editor, mark: TextMark): void {
|
||||
if (isMarkActive(editor, mark)) Editor.removeMark(editor, mark);
|
||||
else Editor.addMark(editor, mark, true);
|
||||
}
|
||||
|
||||
export function activeColor(editor: Editor): string | undefined {
|
||||
const marks = Editor.marks(editor) as CustomText | null;
|
||||
return marks?.color;
|
||||
}
|
||||
|
||||
export function setColor(editor: Editor, color: string): void {
|
||||
Editor.addMark(editor, 'color', color);
|
||||
}
|
||||
|
||||
export function clearColor(editor: Editor): void {
|
||||
Editor.removeMark(editor, 'color');
|
||||
}
|
||||
|
||||
export function insertVariable(editor: Editor, name: string): void {
|
||||
const node: VariableElement = { type: 'variable', name, children: [{ text: '' }] };
|
||||
Transforms.insertNodes(editor, node);
|
||||
Transforms.move(editor); // 삽입된 void 뒤로 커서 이동
|
||||
}
|
||||
|
||||
// ── 직렬화: Slate 값 → 평문(script) ─────────────────────────
|
||||
// 변수는 {name} 토큰으로, 마크는 버리고 텍스트만. 백엔드 script(미리보기) 컬럼에 저장.
|
||||
export function serializeToText(nodes: Descendant[]): string {
|
||||
return nodes.map(serializeNode).join('\n');
|
||||
}
|
||||
|
||||
function serializeNode(node: Descendant): string {
|
||||
if (SlateElement.isElement(node)) {
|
||||
if (node.type === 'variable') return `{${node.name}}`;
|
||||
return node.children.map(serializeNode).join('');
|
||||
}
|
||||
return node.text;
|
||||
}
|
||||
|
||||
// ── 역직렬화: edit_script(JSON) 또는 평문(script) → Slate 값 ──
|
||||
// 저장된 edit_script 가 있으면 그대로, 없으면(레거시 평문 카드) {name} 토큰을 변수 노드로 복원.
|
||||
// Slate 는 initialValue 를 레퍼런스로 직접 변경하므로 항상 새 배열을 돌려준다
|
||||
// (react-query 캐시·공용 상수 오염 방지).
|
||||
export function deserialize(editScript?: unknown, plainText?: string): Descendant[] {
|
||||
if (Array.isArray(editScript) && editScript.length > 0) {
|
||||
return JSON.parse(JSON.stringify(editScript)) as Descendant[];
|
||||
}
|
||||
if (plainText && plainText.trim()) return textToNodes(plainText);
|
||||
return cloneEmpty();
|
||||
}
|
||||
|
||||
function textToNodes(text: string): Descendant[] {
|
||||
return text.split('\n').map((line) => ({ type: 'paragraph' as const, children: lineToChildren(line) }));
|
||||
}
|
||||
|
||||
function lineToChildren(line: string): (CustomText | VariableElement)[] {
|
||||
const children: (CustomText | VariableElement)[] = [];
|
||||
const re = /\{(\w+)\}/g;
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(line)) !== null) {
|
||||
if (m.index > last) children.push({ text: line.slice(last, m.index) });
|
||||
if (isKnownVariable(m[1])) children.push({ type: 'variable', name: m[1], children: [{ text: '' }] });
|
||||
else children.push({ text: m[0] }); // 미등록 토큰은 평문 그대로
|
||||
last = re.lastIndex;
|
||||
}
|
||||
if (last < line.length) children.push({ text: line.slice(last) });
|
||||
return ensureTextEdges(children);
|
||||
}
|
||||
|
||||
// 인라인 void(변수)는 앞뒤·사이에 텍스트 노드가 있어야 한다(Slate normalize 규칙 선반영).
|
||||
function ensureTextEdges(
|
||||
children: (CustomText | VariableElement)[],
|
||||
): (CustomText | VariableElement)[] {
|
||||
const out: (CustomText | VariableElement)[] = [];
|
||||
for (const child of children) {
|
||||
const isVar = 'type' in child;
|
||||
const prev = out[out.length - 1];
|
||||
if (isVar && (!prev || 'type' in prev)) out.push({ text: '' });
|
||||
out.push(child);
|
||||
}
|
||||
const last = out[out.length - 1];
|
||||
if (!out.length || (last && 'type' in last)) out.push({ text: '' });
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useMemo } from 'react';
|
||||
import { withReact } from 'slate-react';
|
||||
import { withHistory } from 'slate-history';
|
||||
import { createCardEditor, withVariables } from './slate';
|
||||
|
||||
// 카드 스크립트용 Slate 에디터 인스턴스.
|
||||
// 조합 순서: createEditor → withReact(React 바인딩) → withHistory(undo/redo) → withVariables(변수 노드).
|
||||
export function useCardScriptEditor() {
|
||||
return useMemo(() => withVariables(withHistory(withReact(createCardEditor()))), []);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// 협상카드 스크립트에 끼워 넣는 치환 변수 카탈로그.
|
||||
// negowiz 는 Zustand 전역 스토어로 들고 있었지만, 여기선 결합도를 낮추려 순수 상수로 둔다.
|
||||
// 저장 포맷의 토큰은 {name} (단일 중괄호) — 백엔드/기존 카드 hint 와 동일 표기.
|
||||
|
||||
export type CardVariable = {
|
||||
name: string; // 토큰/직렬화 키 (예: target_price)
|
||||
label: string; // 칩·툴바에 보이는 한글 라벨 (예: 목표가)
|
||||
};
|
||||
|
||||
export const CARD_VARIABLES: CardVariable[] = [
|
||||
{ name: 'target_price', label: '목표가' },
|
||||
{ name: 'anchor_price', label: '앵커가' },
|
||||
{ name: 'partner_name', label: '협력사명' },
|
||||
{ name: 'product_name', label: '상품명' },
|
||||
];
|
||||
|
||||
const VARIABLE_NAMES = new Set(CARD_VARIABLES.map((v) => v.name));
|
||||
|
||||
export const isKnownVariable = (name: string): boolean => VARIABLE_NAMES.has(name);
|
||||
|
||||
export const variableLabel = (name: string): string =>
|
||||
CARD_VARIABLES.find((v) => v.name === name)?.label ?? name;
|
||||
@@ -6,18 +6,21 @@ import {
|
||||
deleteCard,
|
||||
getListCardsQueryKey,
|
||||
} from '@/api/generated/card/card';
|
||||
import type { Descendant } from 'slate';
|
||||
import type { ReqCreateCard } from '@/api/generated/model/reqCreateCard';
|
||||
import type { ResCard } from '@/api/generated/model/resCard';
|
||||
import type { NegotiationCard } from '@/types';
|
||||
import { generateSlateJSON, mapCardData, toCardStatusCode } from '../types';
|
||||
import { mapCardData, toCardStatusCode } from '../types';
|
||||
import { serializeToText } from '../editor';
|
||||
|
||||
const LIST_PARAMS = { size: 100 };
|
||||
|
||||
// 카드 폼이 넘기는 입력값(편집/생성 공통).
|
||||
// 스크립트는 Slate JSON(editorScript)을 정본으로 받고, 평문 script 는 저장 시 직렬화로 파생한다.
|
||||
export type CardInput = {
|
||||
title: string;
|
||||
code: string;
|
||||
scriptPreview: string;
|
||||
editorScript: Descendant[];
|
||||
status: 'ACTIVE' | 'INACTIVE';
|
||||
isWildcard: boolean;
|
||||
triggerCondition?: string;
|
||||
@@ -37,8 +40,8 @@ function toReq(input: CardInput): ReqCreateCard {
|
||||
is_wildcard: input.isWildcard,
|
||||
name: input.title,
|
||||
number: input.code,
|
||||
script: input.scriptPreview,
|
||||
edit_script: generateSlateJSON(input.scriptPreview),
|
||||
script: serializeToText(input.editorScript), // 평문 미리보기({변수} 토큰 포함)
|
||||
edit_script: input.editorScript, // Slate JSON 원본
|
||||
status: toCardStatusCode(input.status),
|
||||
condition: input.isWildcard ? input.triggerCondition : undefined,
|
||||
memo: input.isWildcard ? input.memo : undefined,
|
||||
|
||||
@@ -29,16 +29,6 @@ export function mapCardData(c: CardData): NegotiationCard {
|
||||
};
|
||||
}
|
||||
|
||||
// 평문 스크립트를 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)}`;
|
||||
@@ -52,14 +52,7 @@ export function PartnerTable({
|
||||
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>
|
||||
),
|
||||
cell: (part) => <span className="font-bold text-sm text-foreground">{part.name}</span>,
|
||||
},
|
||||
{
|
||||
header: '협력사코드',
|
||||
@@ -70,6 +63,7 @@ export function PartnerTable({
|
||||
{
|
||||
header: '담당자명 / 담당자 이메일 / 연락처',
|
||||
align: 'left',
|
||||
mobileBlock: true, // 여러 줄 블록 → 모바일 카드뷰에서 라벨 아래 풀폭
|
||||
cell: (part) => (
|
||||
<div className="space-y-0.5 font-mono text-xs">
|
||||
<div className="text-foreground font-semibold">{part.manager_name}</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from 'zod';
|
||||
import type { ReqCreateItem as ItemCreate } from '@/api/generated/model/reqCreateItem';
|
||||
import type { ReqUpdateItem as ItemUpdate } from '@/api/generated/model/reqUpdateItem';
|
||||
import { useListEnums } from '@/api/generated/enums/enums';
|
||||
import { uploadItemImage } from '@/api/generated/item/item';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import ImageDropzone from '@/components/ImageDropzone';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
@@ -172,6 +173,18 @@ export function ProductFormSheet({
|
||||
}
|
||||
};
|
||||
|
||||
// 드롭존에서 선택/드롭한 파일을 Azure Blob 에 올리고 image_url 을 돌려준다.
|
||||
const handleUploadImage = async (file: File): Promise<string> => {
|
||||
const res = await uploadItemImage({ file: file as unknown as string });
|
||||
if (res.result?.success === false) {
|
||||
throw new Error(res.result.desc || '이미지 업로드에 실패했습니다.');
|
||||
}
|
||||
if (!res.image_url) {
|
||||
throw new Error('이미지 업로드 응답에 URL 이 없습니다.');
|
||||
}
|
||||
return res.image_url;
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={open}
|
||||
@@ -411,6 +424,7 @@ export function ProductFormSheet({
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onClear={() => field.onChange('')}
|
||||
onUpload={handleUploadImage}
|
||||
label="대표이미지 URL"
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import {
|
||||
StopCircle,
|
||||
X,
|
||||
UserCheck,
|
||||
MessageSquare,
|
||||
Layers,
|
||||
Info,
|
||||
Sparkles,
|
||||
Package,
|
||||
} from 'lucide-react';
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import SlateRenderer from '@/components/SlateRenderer';
|
||||
import {
|
||||
useGetQuotationSessions,
|
||||
useGetSessionChat,
|
||||
@@ -66,6 +68,24 @@ export function QuotationDetailDrawer({
|
||||
const currentSession = serverSessions.find((s) => s.session_id === effectiveSessionId);
|
||||
const currentSupplierName =
|
||||
partners.find((p) => p.id === currentSession?.supplier_id)?.name || currentSession?.supplier_id || '-';
|
||||
// 현재 세션의 상품(이미지·규격 등 상세 + 카드 변수 치환용 상품명).
|
||||
const currentProduct = products.find((p) => p.id === currentSession?.item_id);
|
||||
// 상품 상세 패널 행(negowiz 협상대화의 상품 정보 대응). negodata 컬럼명: maker_name→manufacturer, min_order_quantity→moq.
|
||||
const fmtYn = (b: boolean | null | undefined, yes: string, no: string) => (b == null ? '-' : b ? yes : no);
|
||||
const productSpecRows = currentProduct
|
||||
? [
|
||||
{ label: '상품코드', value: currentProduct.code || '-' },
|
||||
{ label: '단가', value: currentProduct.price != null ? `₩${Number(currentProduct.price).toLocaleString()}` : '-' },
|
||||
{ label: '모델명', value: currentProduct.model_name || '-' },
|
||||
{ label: '규격', value: currentProduct.spec || '-' },
|
||||
{ label: '제조사', value: currentProduct.manufacturer || '-' },
|
||||
{ label: '원산지', value: currentProduct.made_in || '-' },
|
||||
{ label: 'MOQ', value: currentProduct.moq || '-' },
|
||||
{ label: '리드타임', value: currentProduct.lead_time != null ? `${currentProduct.lead_time}일` : '-' },
|
||||
{ label: 'VAT', value: fmtYn(currentProduct.vat_yn, '포함', '별도') },
|
||||
{ label: '배송비', value: fmtYn(currentProduct.delivery_fee_yn, '포함', '별도') },
|
||||
]
|
||||
: [];
|
||||
|
||||
const selectedSettingObj = quotationSettings.find((qs) => qs.qt_setting_id === estimate.settingApplied);
|
||||
|
||||
@@ -93,7 +113,7 @@ export function QuotationDetailDrawer({
|
||||
const tabs: { id: DrawerTab; label: string; icon: typeof UserCheck }[] = [
|
||||
{ id: 'status', label: '협상 현황', icon: UserCheck },
|
||||
{ id: 'chat', label: '협상 대화', icon: MessageSquare },
|
||||
{ id: 'cards', label: '협상 카드', icon: Layers },
|
||||
{ id: 'cards', label: `협상 카드 (${serverCards.length})`, icon: Layers },
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -117,7 +137,7 @@ export function QuotationDetailDrawer({
|
||||
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>
|
||||
<span>{showHeaderCards ? '견적 상세 정보 접기 ▲' : '견적 상세 정보 펼치기 ▼'}</span>
|
||||
</button>
|
||||
{statusKey === '견적진행중' && (
|
||||
<button
|
||||
@@ -139,33 +159,35 @@ export function QuotationDetailDrawer({
|
||||
|
||||
{/* DB mapping info cards */}
|
||||
{showHeaderCards && (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mt-4 text-xs font-mono">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4 text-xs font-mono">
|
||||
{/* 좌측 컬럼: 견적정보 + 진행상태 */}
|
||||
<div className="space-y-4">
|
||||
{/* 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-[10px] block opacity-70">견적명</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-[10px] block opacity-70">견적번호</span>
|
||||
<span className="text-foreground font-semibold">{q_number}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[10px] block opacity-70">유형 (type)</span>
|
||||
<span className="text-[10px] block opacity-70">유형</span>
|
||||
<span className="text-foreground font-semibold">
|
||||
{q_type === 'RE_NEGOTIATION' ? '재협상 (RE_NEGOTIATION)' : '재견적 (RE_ESTIMATE)'}
|
||||
{q_type === 'RE_NEGOTIATION' ? '재협상' : '재견적'}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[10px] block opacity-70">차수 (round)</span>
|
||||
<span className="text-foreground font-semibold">{q_round}차 (round)</span>
|
||||
<span className="text-[10px] block opacity-70">차수</span>
|
||||
<span className="text-foreground font-semibold">{q_round}차</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[10px] block opacity-90 font-bold mb-1">견적상태 (status)</span>
|
||||
<span className="text-[10px] block opacity-90 font-bold mb-1">견적상태</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 === '견적생성'
|
||||
@@ -196,15 +218,15 @@ export function QuotationDetailDrawer({
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[10px] block opacity-70">마감시각 (end_time)</span>
|
||||
<span className="text-[10px] block opacity-70">마감시각</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-[10px] block opacity-70">담당자</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-[10px] block opacity-70">메모</span>
|
||||
<span className="text-foreground font-semibold font-sans truncate block" title={q_memo || ''}>
|
||||
{q_memo}
|
||||
</span>
|
||||
@@ -215,69 +237,103 @@ export function QuotationDetailDrawer({
|
||||
{/* 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-[10px] block opacity-70">식별자</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-[10px] block opacity-70">진행/결과 상태</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>
|
||||
<span className="text-[10px] block opacity-70">반복횟수</span>
|
||||
<span className="text-foreground font-semibold">{bidSummaryObj.qt_iteration}회</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[10px] block opacity-70">우선협상자 존재여부 (has_preferred)</span>
|
||||
<span className="text-[10px] block opacity-70">우선협상자 존재여부</span>
|
||||
<span className={`text-foreground font-semibold ${bidSummaryObj.has_preferred ? 'text-emerald-600 font-bold' : ''}`}>
|
||||
{bidSummaryObj.has_preferred ? '존재 (true)' : '미존재 (false)'}
|
||||
{bidSummaryObj.has_preferred ? '존재' : '미존재'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<span className="text-[10px] block opacity-70">우선협상자명 (preferred_sp_name)</span>
|
||||
<span className="text-[10px] block opacity-70">우선협상자명</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>
|
||||
<span className="text-[10px] block opacity-70">동가입찰정보</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>
|
||||
</div>
|
||||
|
||||
{/* 우측 컬럼: 상품정보 + 세팅 */}
|
||||
<div className="space-y-4">
|
||||
{/* 상품 정보 (협상 대상 상품) */}
|
||||
<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">
|
||||
상품 정보
|
||||
</span>
|
||||
{currentProduct ? (
|
||||
<div className="flex gap-4">
|
||||
<div className="h-24 w-24 shrink-0 rounded-md border border-border bg-background overflow-hidden flex items-center justify-center">
|
||||
{currentProduct.image_url ? (
|
||||
<img
|
||||
src={currentProduct.image_url}
|
||||
alt={currentProduct.name || '상품'}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Package size={28} className="text-muted-foreground/50" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<Link
|
||||
to={`/products?edit=${currentProduct.id}`}
|
||||
className="text-foreground font-bold font-sans text-[12px] mb-2 truncate block hover:text-primary hover:underline"
|
||||
title={`${currentProduct.name || ''} — 상품 상세로 이동`}
|
||||
>
|
||||
{currentProduct.name || '-'}
|
||||
</Link>
|
||||
<div className="grid grid-cols-2 lg:grid-cols-3 gap-x-3 gap-y-1.5 font-mono text-muted-foreground">
|
||||
{productSpecRows.map((r) => (
|
||||
<div key={r.label}>
|
||||
<span className="text-[10px] block opacity-70">{r.label}</span>
|
||||
<span className="text-foreground font-semibold font-sans truncate block" title={r.value}>
|
||||
{r.value}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground py-6 text-center">상품 정보가 비어있습니다.</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-[10px] block opacity-70">목표 마진율</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-[10px] block opacity-70">앵커링 설정 값</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-[10px] block opacity-70">카드 사용 횟수</span>
|
||||
<span className="text-foreground font-semibold">{selectedSettingObj.card_use_count}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -285,6 +341,7 @@ export function QuotationDetailDrawer({
|
||||
<div className="text-muted-foreground py-6 text-center">적용된 견적 세팅이 비어있습니다.</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -299,8 +356,12 @@ export function QuotationDetailDrawer({
|
||||
key={tab.id}
|
||||
onClick={() => {
|
||||
setActiveTab(tab.id);
|
||||
if (tab.id === 'chat' && serverSessions.length > 0 && !selectedSessionId) {
|
||||
setSelectedSessionId(serverSessions[0].session_id);
|
||||
if (tab.id === 'chat') {
|
||||
// 협상 대화 탭에선 대화 영역을 넓게 쓰도록 견적 상세 정보를 접는다.
|
||||
setShowHeaderCards(false);
|
||||
if (serverSessions.length > 0 && !selectedSessionId) {
|
||||
setSelectedSessionId(serverSessions[0].session_id);
|
||||
}
|
||||
}
|
||||
}}
|
||||
className={`flex items-center gap-2 py-4 px-3 text-xs tracking-tight font-semibold border-b-2 transition-all cursor-pointer ${
|
||||
@@ -399,11 +460,6 @@ export function QuotationDetailDrawer({
|
||||
{/* 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">
|
||||
@@ -418,7 +474,19 @@ export function QuotationDetailDrawer({
|
||||
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 text-foreground font-sans font-semibold">
|
||||
{qc.card_id ? (
|
||||
<Link
|
||||
to={`/cards?edit=${qc.card_id}`}
|
||||
className="hover:text-primary hover:underline"
|
||||
title={`${qc.card_name} — 협상카드 상세로 이동`}
|
||||
>
|
||||
{qc.card_name}
|
||||
</Link>
|
||||
) : (
|
||||
qc.card_name
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="p-3">
|
||||
<span
|
||||
className={`inline-flex px-2 py-0.5 rounded text-[10px] font-bold ${
|
||||
@@ -501,7 +569,7 @@ export function QuotationDetailDrawer({
|
||||
<div className="flex-1 flex flex-col bg-background justify-between">
|
||||
<div className="p-3 bg-muted/30 border-b border-border text-xs flex items-center justify-between font-mono">
|
||||
<div className="text-muted-foreground">
|
||||
채널: <strong className="text-foreground">{currentSupplierName}</strong>
|
||||
협력사: <strong className="text-foreground">{currentSupplierName}</strong>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
기록: <span className="font-semibold text-foreground">{chatMessages.length}</span> 메시지
|
||||
@@ -511,7 +579,7 @@ export function QuotationDetailDrawer({
|
||||
<div className="flex-1 p-4 overflow-y-auto space-y-4">
|
||||
{!effectiveSessionId ? (
|
||||
<div className="h-full flex items-center justify-center text-muted-foreground font-mono text-xs">
|
||||
선택된 대화 채널이 없습니다.
|
||||
선택된 협력사가 없습니다.
|
||||
</div>
|
||||
) : chatMessages.length === 0 ? (
|
||||
<div className="h-full flex items-center justify-center text-muted-foreground font-mono text-xs">
|
||||
@@ -520,25 +588,20 @@ export function QuotationDetailDrawer({
|
||||
) : (
|
||||
chatMessages.map((m) => {
|
||||
const isBot = m.sender === 1;
|
||||
const cardName = m.card_used_yn
|
||||
? serverCards.find((c) => c.session_card_id === m.chat_id)?.name
|
||||
: null;
|
||||
// 메시지가 쓴 협상카드 전체(이름만이 아니라 멘트/조건/메모까지) 를 chat_id 로 매칭.
|
||||
const usedCard = m.card_used_yn
|
||||
? serverCards.find((c) => c.session_card_id === m.chat_id)
|
||||
: undefined;
|
||||
const cardNodes = Array.isArray(usedCard?.edit_script) ? (usedCard.edit_script as unknown[]) : null;
|
||||
const isWildCard = usedCard?.type === 2;
|
||||
return (
|
||||
<div
|
||||
key={m.chat_id}
|
||||
className={`flex items-start gap-2.5 max-w-[85%] ${isBot ? 'mr-auto' : 'ml-auto flex-row-reverse'}`}
|
||||
className={`flex ${isBot ? 'justify-start' : 'justify-end'}`}
|
||||
>
|
||||
<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="space-y-1 max-w-[85%]">
|
||||
<div className={`text-[10px] text-muted-foreground font-mono flex items-center gap-1.5 ${isBot ? '' : 'justify-end'}`}>
|
||||
<span>{isBot ? 'Negosium AI Bot' : currentSupplierName}</span>
|
||||
<span>{isBot ? 'Negosium Bot' : currentSupplierName}</span>
|
||||
<span>·</span>
|
||||
<span>#{m.index}</span>
|
||||
</div>
|
||||
@@ -549,13 +612,68 @@ export function QuotationDetailDrawer({
|
||||
}`}
|
||||
>
|
||||
<div className="font-bold">제시 단가 ₩{Number(m.target_price).toLocaleString()}</div>
|
||||
{cardName && (
|
||||
{usedCard && (
|
||||
<div
|
||||
className={`mt-1.5 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold ${
|
||||
isBot ? 'bg-amber-100 text-amber-800 dark:bg-amber-950/30 dark:text-amber-300' : 'bg-white/20'
|
||||
className={`mt-2 rounded border p-2 ${
|
||||
isBot
|
||||
? 'bg-amber-50/70 border-amber-200 dark:bg-amber-950/20 dark:border-amber-900/40'
|
||||
: 'bg-white/10 border-white/20'
|
||||
}`}
|
||||
>
|
||||
<Sparkles size={10} /> 협상카드: {cardName}
|
||||
{/* 헤더: 어떤 카드인지(번호·이름·종류) */}
|
||||
<div
|
||||
className={`flex items-center gap-1 text-[10px] font-semibold ${
|
||||
isBot ? 'text-amber-800 dark:text-amber-300' : 'text-primary-foreground'
|
||||
}`}
|
||||
>
|
||||
<Sparkles size={10} />
|
||||
<span>협상카드</span>
|
||||
{usedCard.number && <span className="font-mono opacity-70">#{usedCard.number}</span>}
|
||||
{usedCard.name && <span>· {usedCard.name}</span>}
|
||||
<span
|
||||
className={`ml-auto px-1.5 py-0.5 rounded font-bold ${
|
||||
isWildCard
|
||||
? 'bg-amber-200 text-amber-900 dark:bg-amber-400/25 dark:text-amber-100'
|
||||
: 'bg-zinc-200 text-zinc-700 dark:bg-zinc-600/40 dark:text-zinc-100'
|
||||
}`}
|
||||
>
|
||||
{isWildCard ? '와일드' : '협상'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 멘트 본문: 서식본(edit_script) 우선, 없으면 평문 script */}
|
||||
{cardNodes ? (
|
||||
<div className="mt-1.5">
|
||||
<SlateRenderer
|
||||
nodes={cardNodes}
|
||||
variables={{
|
||||
target_price: m.target_price,
|
||||
partner_name: currentSupplierName,
|
||||
product_name: currentProduct?.name ?? '',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : usedCard.script ? (
|
||||
<p className="mt-1.5 text-xs leading-relaxed whitespace-pre-line text-foreground/85">
|
||||
{usedCard.script}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{/* 와일드카드 부가 정보: 사용 조건 / 메모 */}
|
||||
{isWildCard && (usedCard.condition || usedCard.memo) && (
|
||||
<div className="mt-1.5 pt-1.5 border-t border-amber-200/60 dark:border-amber-900/40 space-y-0.5 text-[10px] text-muted-foreground">
|
||||
{usedCard.condition && (
|
||||
<div>
|
||||
<span className="font-semibold">조건:</span> {usedCard.condition}
|
||||
</div>
|
||||
)}
|
||||
{usedCard.memo && (
|
||||
<div>
|
||||
<span className="font-semibold">메모:</span> {usedCard.memo}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Eye, StopCircle, Clock, Building2 } from 'lucide-react';
|
||||
import { Clock, Building2 } from 'lucide-react';
|
||||
import { DataTable } from '@/components/ui/data-table';
|
||||
import { type Estimate, type Product, normalizeQuotationStatus } from '../types';
|
||||
|
||||
@@ -6,7 +6,6 @@ type QuotationTableProps = {
|
||||
data: Estimate[];
|
||||
products: Product[];
|
||||
onOpenDetail: (id: string) => void;
|
||||
onStop: (id: string, title: string) => void;
|
||||
};
|
||||
|
||||
const statusBadgeClass = (status?: string | null) => {
|
||||
@@ -24,7 +23,7 @@ const statusBadgeClass = (status?: string | null) => {
|
||||
}
|
||||
};
|
||||
|
||||
export function QuotationTable({ data, products, onOpenDetail, onStop }: QuotationTableProps) {
|
||||
export function QuotationTable({ data, products, onOpenDetail }: QuotationTableProps) {
|
||||
return (
|
||||
<DataTable
|
||||
data={data}
|
||||
@@ -102,37 +101,6 @@ export function QuotationTable({ data, products, onOpenDetail, onStop }: Quotati
|
||||
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>
|
||||
|
||||
{normalizeQuotationStatus(est.status) === '견적진행중' && (
|
||||
<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>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ import type { QuotationSettingData } from '@/api/generated/model/quotationSettin
|
||||
import type { QuotationData } from '@/api/generated/model/quotationData';
|
||||
import type { CardData } from '@/api/generated/model/cardData';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { confirm } from '@/lib/confirm';
|
||||
import type { Estimate, ChatSession, Product } from '@/types';
|
||||
import { unwrap, mapItem, mapSupplier, mapSetting, mapQuotation } from '../types';
|
||||
|
||||
@@ -68,8 +69,8 @@ export function useQuotations() {
|
||||
const [chatSessions, setChatSessions] = useState<Record<string, ChatSession[]>>({});
|
||||
|
||||
// 협상 강제중단 → '협상보류'.
|
||||
const stopNegotiation = (id: string, name: string) => {
|
||||
if (!confirm(`현재 입찰 중인 [${name}] 단가 협상 절차를 즉시 조기 중단(강제종료)하시겠습니까?`)) return;
|
||||
const stopNegotiation = async (id: string, name: string) => {
|
||||
if (!(await confirm({ title: '협상 강제중단', description: `현재 입찰 중인 [${name}] 단가 협상 절차를 즉시 조기 중단(강제종료)하시겠습니까?`, confirmText: '중단', destructive: true }))) return;
|
||||
setQuotations((prev) => prev.map((e) => (e.id === id ? { ...e, status: '협상보류' } : e)));
|
||||
showToast("해당 협상이 관리자에 의하여 '협상보류' 상태로 지정되었습니다.", 'info');
|
||||
};
|
||||
@@ -101,12 +102,12 @@ export function useQuotations() {
|
||||
};
|
||||
|
||||
// 견적 세팅 삭제(서버 soft-delete, 최소 1개 유지).
|
||||
const deleteSetting = (id: string) => {
|
||||
const deleteSetting = async (id: string) => {
|
||||
if (quotationSettings.length <= 1) {
|
||||
showToast('최소 한 개의 세팅은 유지되어야 합니다.', 'error');
|
||||
return;
|
||||
}
|
||||
if (!confirm('선택한 견적 세팅을 삭제하시겠습니까?')) return;
|
||||
if (!(await confirm({ title: '견적 세팅 삭제', description: '선택한 견적 세팅을 삭제하시겠습니까?', confirmText: '삭제', destructive: true }))) return;
|
||||
deleteSettingMutation.mutate(
|
||||
{ qtSettingId: id },
|
||||
{
|
||||
|
||||
@@ -70,7 +70,7 @@ export function mapQuotation(q: QuotationData): Estimate {
|
||||
status: normalizeQuotationStatus(q.status) || String(q.status ?? ''),
|
||||
settingApplied: q.qt_setting_id, // 드로어 견적세팅 카드가 qt_setting_id 로 매칭
|
||||
dueDate: formatDueDate(q.end_time),
|
||||
participationCount: 0,
|
||||
participationCount: q.participation_count ?? 0,
|
||||
winnerPartnerId: q.preferred_sp_id ?? q.preferred_sp_name ?? null,
|
||||
isEqualPrice: !!q.equal_bid_yn,
|
||||
partnerIds: [],
|
||||
@@ -160,6 +160,7 @@ export type SessionView = {
|
||||
|
||||
export type QuotationCardView = {
|
||||
session_card_id: string;
|
||||
card_id: string | null; // 실제 카드 id(협상=nego_card_id, 와일드=wild_card_id) — /cards?edit= 링크용
|
||||
card_name: string;
|
||||
type: string;
|
||||
};
|
||||
@@ -295,6 +296,7 @@ export function mapServerSessionView(sd: SessionData, partners: Partner[], produ
|
||||
export function mapServerCardView(c: QuotationCardData): QuotationCardView {
|
||||
return {
|
||||
session_card_id: c.session_card_id,
|
||||
card_id: c.nego_card_id ?? c.wild_card_id ?? null,
|
||||
card_name: c.name || '-',
|
||||
type: c.type === 2 ? '와일드 카드' : '협상 카드',
|
||||
};
|
||||
@@ -306,6 +308,7 @@ export function buildQuotationCards(est: Estimate, cards: NegotiationCard[]): Qu
|
||||
const matchedCard = cards.find((c) => c.id === cId);
|
||||
return {
|
||||
session_card_id: `scard-${est.id}-${cId}`,
|
||||
card_id: cId,
|
||||
card_name: matchedCard?.title || '-',
|
||||
type: matchedCard?.isWildcard ? '와일드 카드' : '협상 카드',
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user