import { Fragment, useEffect, useMemo, useRef, useState, type ElementType } from 'react'; import { useSearchParams } from 'react-router'; import { useQuery } from '@tanstack/react-query'; import { Palette, Tags, ListPlus, MessageSquareText, Plus, Trash2, RotateCcw, Download, Upload, X } from 'lucide-react'; import { showToast } from '@/lib/notify'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import ImageDropzone from '@/components/ImageDropzone'; import { uploadItemImage } from '@/api/generated/item/item'; import { previewInviteEmail } from '@/api/generated/company-settings/company-settings'; import { Badge } from '@/components/ui/badge'; import { Typography } from '@/components/ui/typography'; import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'; import { Select, SelectValue, SelectTrigger, SelectContent, SelectItem } from '@/components/ui/select'; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table'; import { LABEL_CATALOG, LABEL_DEFAULTS, HIDEABLE_ITEM_FIELDS, CUSTOM_FIELD_TYPE_LABEL, DEFAULT_GUIDE_NOTICES, NEGO_BASELINE_OPTIONS, DEFAULT_NEGO_BASELINE_FIELD, VAT_MODE_OPTIONS, DEFAULT_VAT_MODE, type CompanySettings, type CustomFieldDef, type CustomFieldType, type NegoBaselineField, } from './catalog'; import { useCompanySettings } from './useCompanySettings'; export const SETTINGS_TABS = ['branding', 'portal', 'labels', 'fields'] as const; export type SettingsTab = (typeof SETTINGS_TABS)[number]; export const SETTINGS_TAB_LABEL: Record = { branding: '브랜딩(CI)', portal: '공급사 포털 안내', labels: '용어(라벨)', fields: '커스텀 필드', }; // 화면에 보이는 것(로고·안내 문구)은 회사 관리자가, 협상 동작·데이터 구조를 바꾸는 것은 개발자가 다룬다. // 용어를 바꾸면 협상 멘트 호칭까지 같이 바뀌고, 커스텀 필드 탭의 협상 기준가·필드 숨김은 목표가 산정과 // 학습 기준에 영향을 주므로 개발자 쪽에 둔다. export const OWNER_SETTINGS_TABS: readonly SettingsTab[] = ['branding', 'portal']; export const DEV_SETTINGS_TABS: readonly SettingsTab[] = ['labels', 'fields']; const SETTINGS_TAB_ICON: Record = { branding: Palette, portal: MessageSquareText, labels: Tags, fields: ListPlus, }; // branding 의 문자열 서브키(helpdesk 만 배열이라 제외). email_* 는 협상 초청 메일 커스텀. type BrandingTextKey = | 'service_name' | 'logo_url' | 'email_greeting'; export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly SettingsTab[] }) { const { settings, isLoading, save } = useCompanySettings(); // 탭은 ?tab=<탭> 으로 URL 에 남긴다 — 링크 공유·새로고침·메뉴 빠른이동에서 같은 탭으로 열리게. const [searchParams, setSearchParams] = useSearchParams(); const tabParam = searchParams.get('tab'); const tab: SettingsTab = tabs.includes((tabParam ?? '') as SettingsTab) ? (tabParam as SettingsTab) : tabs[0]; const setTab = (next: string) => { const params = new URLSearchParams(searchParams); params.set('tab', next); setSearchParams(params, { replace: true }); }; // 저장 전 편집본(draft). 서버 반영은 저장 버튼에서만. const [draft, setDraft] = useState({}); const [saving, setSaving] = useState(false); useEffect(() => { if (!isLoading) setDraft(structuredClone(settings)); // settings 객체는 쿼리 캐시 무효화 때만 바뀐다(참조 비교로 충분). // eslint-disable-next-line react-hooks/exhaustive-deps }, [isLoading, JSON.stringify(settings)]); const dirty = useMemo(() => JSON.stringify(draft) !== JSON.stringify(settings), [draft, settings]); const handleSave = async () => { // 빈 문자열 라벨/브랜딩은 "기본값 사용"이므로 저장 전 제거해 문서를 깨끗하게 유지한다. const labels = Object.fromEntries(Object.entries(draft.labels ?? {}).filter(([, v]) => v.trim())); // 브랜딩은 문자열 값만 trim 검사한다 — helpdesk 는 문자열 배열이라 빈 줄만 걸러 따로 싣는다. const { helpdesk: helpdeskDraft, ...brandingText } = draft.branding ?? {}; const helpdesk = (helpdeskDraft ?? []).map((l) => l.trim()).filter(Boolean); const branding: NonNullable = Object.fromEntries(Object.entries(brandingText).filter(([, v]) => (v ?? '').trim())); if (helpdesk.length > 0) branding.helpdesk = helpdesk; const itemFields = (draft.item_fields ?? []).filter((f) => f.key.trim() && f.label.trim()); const supplierFields = (draft.supplier_fields ?? []).filter((f) => f.key.trim() && f.label.trim()); const sessionFields = (draft.session_fields ?? []).filter((f) => f.key.trim() && f.label.trim()); const hiddenFields = [...new Set((draft.hidden_fields ?? []).filter((k) => k.trim()))]; const guideNotices = (draft.guide_notices ?? []).map((l) => l.trim()).filter(Boolean); const next: CompanySettings = { ...draft, hidden_fields: hiddenFields, guide_notices: guideNotices, labels, branding, item_fields: itemFields, supplier_fields: supplierFields, session_fields: sessionFields, }; setSaving(true); try { await save(next); showToast('회사 설정이 저장되었습니다.', 'success'); } catch (err) { showToast(err instanceof Error ? err.message : '설정 저장 실패', 'error'); } finally { setSaving(false); } }; const fileRef = useRef(null); // 현재 편집본을 JSON 파일로 내려받는다(회사 설정 전체 백업/이관용). const handleExport = () => { const blob = new Blob([JSON.stringify(draft, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'company-settings.json'; a.click(); URL.revokeObjectURL(url); }; // JSON 파일 → 편집본 병합. 빈 값(빈 문자열·빈 배열·null)은 "그대로 두기"로 보고 덮어쓰지 않는다. const handleImport = async (file: File) => { try { const parsed = JSON.parse(await file.text()) as CompanySettings; setDraft((d) => mergeSettings(d, parsed)); showToast('설정 JSON 을 불러왔습니다. 확인 후 저장하십시오.', 'success'); } catch (err) { showToast(err instanceof Error ? `JSON 파싱 실패 - ${err.message}` : 'JSON 파싱 실패', 'error'); } }; // 로고 파일 업로드 — 상품 이미지와 동일한 스토리지 엔드포인트(/v1/item/image, Azure Blob)를 재사용해 URL 을 받는다. const handleUploadLogo = async (file: File): Promise => { 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; }; const setBranding = (key: BrandingTextKey, value: string) => setDraft((d) => ({ ...d, branding: { ...d.branding, [key]: value } })); const setHelpdesk = (lines: string[]) => setDraft((d) => ({ ...d, branding: { ...d.branding, helpdesk: lines } })); const setLabel = (key: string, value: string) => setDraft((d) => ({ ...d, labels: { ...d.labels, [key]: value } })); return (
{tabs.map((t) => { const Icon = SETTINGS_TAB_ICON[t]; return ( {SETTINGS_TAB_LABEL[t]} ); })} {/* 저장 바 — 변경이 있을 때만 활성화 */}
{dirty && ( )} { const f = e.target.files?.[0]; if (f) handleImport(f); e.target.value = ''; // 같은 파일 재선택 허용 }} />
{/* ---- 브랜딩(CI) ---- */}
setBranding('service_name', e.target.value)} placeholder="NegoData (기본값)" />
{/* 로고 이미지 — 업로드(드롭/선택) 또는 URL 직접 입력. 비우면 색상 마크+서비스명 텍스트. */}
setBranding('logo_url', url)} onClear={() => setBranding('logo_url', '')} onUpload={handleUploadLogo} label="로고 이미지 업로드" />
{/* 라이브 미리보기 */}
미리보기 — 사이드바 브랜드
{draft.branding?.logo_url ? ( 로고 미리보기 ) : ( )} {draft.branding?.service_name || 'NegoData'}