From 6c751eb489f6bb1e0874932eba2e736895ef158c Mon Sep 17 00:00:00 2001 From: SeongHyun Kim Date: Thu, 4 Dec 2025 17:40:41 +0900 Subject: [PATCH] =?UTF-8?q?feat(universal-form-modal):=20=EB=B2=94?= =?UTF-8?q?=EC=9A=A9=20=ED=8F=BC=20=EB=AA=A8=EB=8B=AC=20=EC=BB=B4=ED=8F=AC?= =?UTF-8?q?=EB=84=8C=ED=8A=B8=20=EC=8B=A0=EA=B7=9C=20=EA=B0=9C=EB=B0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 섹션 기반 폼 레이아웃 지원 (접힘/펼침, 그리드 컬럼) - 반복 섹션 지원 (겸직 등 동일 필드 그룹 여러 개 추가) - 채번규칙 연동 (모달 열릴 때 또는 저장 시점 자동 생성) - 다중 행 저장 지원 (공통 필드 + 개별 필드 조합) - Select 옵션 동적 로드 (정적/테이블/공통코드) - 스크린 디자이너 설정 패널 구현 --- frontend/lib/registry/components/index.ts | 3 + .../UniversalFormModalComponent.tsx | 951 ++++++++++++++ .../UniversalFormModalConfigPanel.tsx | 1152 +++++++++++++++++ .../UniversalFormModalRenderer.tsx | 35 + .../components/universal-form-modal/config.ts | 138 ++ .../components/universal-form-modal/index.ts | 77 ++ .../components/universal-form-modal/types.ts | 259 ++++ 7 files changed, 2615 insertions(+) create mode 100644 frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx create mode 100644 frontend/lib/registry/components/universal-form-modal/UniversalFormModalConfigPanel.tsx create mode 100644 frontend/lib/registry/components/universal-form-modal/UniversalFormModalRenderer.tsx create mode 100644 frontend/lib/registry/components/universal-form-modal/config.ts create mode 100644 frontend/lib/registry/components/universal-form-modal/index.ts create mode 100644 frontend/lib/registry/components/universal-form-modal/types.ts diff --git a/frontend/lib/registry/components/index.ts b/frontend/lib/registry/components/index.ts index 746e2c2d..2a5d45e4 100644 --- a/frontend/lib/registry/components/index.ts +++ b/frontend/lib/registry/components/index.ts @@ -74,6 +74,9 @@ import "./location-swap-selector/LocationSwapSelectorRenderer"; // 🆕 화면 임베딩 및 분할 패널 컴포넌트 import "./screen-split-panel/ScreenSplitPanelRenderer"; // 화면 분할 패널 (좌우 화면 임베딩 + 데이터 전달) +// 🆕 범용 폼 모달 컴포넌트 +import "./universal-form-modal/UniversalFormModalRenderer"; // 섹션 기반 폼, 채번규칙, 다중 행 저장 지원 + /** * 컴포넌트 초기화 함수 */ diff --git a/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx new file mode 100644 index 00000000..c4501f6b --- /dev/null +++ b/frontend/lib/registry/components/universal-form-modal/UniversalFormModalComponent.tsx @@ -0,0 +1,951 @@ +"use client"; + +import React, { useState, useEffect, useCallback, useMemo } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; +import { ChevronDown, ChevronUp, Plus, Trash2, RefreshCw } from "lucide-react"; +import { toast } from "sonner"; +import { cn } from "@/lib/utils"; +import { apiClient } from "@/lib/api/client"; +import { generateNumberingCode } from "@/lib/api/numberingRule"; + +import { + UniversalFormModalComponentProps, + UniversalFormModalConfig, + FormSectionConfig, + FormFieldConfig, + FormDataState, + RepeatSectionItem, + SelectOptionConfig, +} from "./types"; +import { defaultConfig, generateUniqueId } from "./config"; + +/** + * 범용 폼 모달 컴포넌트 + * + * 섹션 기반 폼 레이아웃, 채번규칙, 다중 행 저장을 지원합니다. + */ +export function UniversalFormModalComponent({ + component, + config: propConfig, + isDesignMode = false, + isSelected = false, + className, + style, + initialData, + onSave, + onCancel, + onChange, +}: UniversalFormModalComponentProps) { + // 설정 병합 + const config: UniversalFormModalConfig = useMemo(() => { + const componentConfig = component?.config || {}; + return { + ...defaultConfig, + ...propConfig, + ...componentConfig, + modal: { + ...defaultConfig.modal, + ...propConfig?.modal, + ...componentConfig.modal, + }, + saveConfig: { + ...defaultConfig.saveConfig, + ...propConfig?.saveConfig, + ...componentConfig.saveConfig, + multiRowSave: { + ...defaultConfig.saveConfig.multiRowSave, + ...propConfig?.saveConfig?.multiRowSave, + ...componentConfig.saveConfig?.multiRowSave, + }, + afterSave: { + ...defaultConfig.saveConfig.afterSave, + ...propConfig?.saveConfig?.afterSave, + ...componentConfig.saveConfig?.afterSave, + }, + }, + }; + }, [component?.config, propConfig]); + + // 폼 데이터 상태 + const [formData, setFormData] = useState({}); + const [, setOriginalData] = useState>({}); + + // 반복 섹션 데이터 + const [repeatSections, setRepeatSections] = useState<{ + [sectionId: string]: RepeatSectionItem[]; + }>({}); + + // 섹션 접힘 상태 + const [collapsedSections, setCollapsedSections] = useState>(new Set()); + + // Select 옵션 캐시 + const [selectOptionsCache, setSelectOptionsCache] = useState<{ + [key: string]: { value: string; label: string }[]; + }>({}); + + // 로딩 상태 + const [saving, setSaving] = useState(false); + + // 삭제 확인 다이얼로그 + const [deleteDialog, setDeleteDialog] = useState<{ + open: boolean; + sectionId: string; + itemId: string; + }>({ open: false, sectionId: "", itemId: "" }); + + // 초기화 + useEffect(() => { + initializeForm(); + }, [config, initialData]); + + // 폼 초기화 + const initializeForm = useCallback(async () => { + const newFormData: FormDataState = {}; + const newRepeatSections: { [sectionId: string]: RepeatSectionItem[] } = {}; + const newCollapsed = new Set(); + + // 섹션별 초기화 + for (const section of config.sections) { + // 접힘 상태 초기화 + if (section.defaultCollapsed) { + newCollapsed.add(section.id); + } + + if (section.repeatable) { + // 반복 섹션 초기화 + const minItems = section.repeatConfig?.minItems || 0; + const items: RepeatSectionItem[] = []; + for (let i = 0; i < minItems; i++) { + items.push(createRepeatItem(section, i)); + } + newRepeatSections[section.id] = items; + } else { + // 일반 섹션 필드 초기화 + for (const field of section.fields) { + // 기본값 설정 + let value = field.defaultValue ?? ""; + + // 부모에서 전달받은 값 적용 + if (field.receiveFromParent && initialData) { + const parentField = field.parentFieldName || field.columnName; + if (initialData[parentField] !== undefined) { + value = initialData[parentField]; + } + } + + newFormData[field.columnName] = value; + } + } + } + + setFormData(newFormData); + setRepeatSections(newRepeatSections); + setCollapsedSections(newCollapsed); + setOriginalData(initialData || {}); + + // 채번규칙 자동 생성 + await generateNumberingValues(newFormData); + }, [config, initialData]); + + // 반복 섹션 아이템 생성 + const createRepeatItem = (section: FormSectionConfig, index: number): RepeatSectionItem => { + const item: RepeatSectionItem = { + _id: generateUniqueId("repeat"), + _index: index, + }; + + for (const field of section.fields) { + item[field.columnName] = field.defaultValue ?? ""; + } + + return item; + }; + + // 채번규칙 자동 생성 + const generateNumberingValues = useCallback( + async (currentFormData: FormDataState) => { + const updatedData = { ...currentFormData }; + let hasChanges = false; + + for (const section of config.sections) { + if (section.repeatable) continue; + + for (const field of section.fields) { + if ( + field.numberingRule?.enabled && + field.numberingRule?.generateOnOpen && + field.numberingRule?.ruleId && + !updatedData[field.columnName] + ) { + try { + const response = await generateNumberingCode(field.numberingRule.ruleId); + if (response.success && response.data?.generatedCode) { + updatedData[field.columnName] = response.data.generatedCode; + hasChanges = true; + } + } catch (error) { + console.error(`채번규칙 생성 실패 (${field.columnName}):`, error); + } + } + } + } + + if (hasChanges) { + setFormData(updatedData); + } + }, + [config], + ); + + // 필드 값 변경 핸들러 + const handleFieldChange = useCallback( + (columnName: string, value: any) => { + setFormData((prev) => { + const newData = { ...prev, [columnName]: value }; + onChange?.(newData); + return newData; + }); + }, + [onChange], + ); + + // 반복 섹션 필드 값 변경 핸들러 + const handleRepeatFieldChange = useCallback((sectionId: string, itemId: string, columnName: string, value: any) => { + setRepeatSections((prev) => { + const items = prev[sectionId] || []; + const newItems = items.map((item) => (item._id === itemId ? { ...item, [columnName]: value } : item)); + return { ...prev, [sectionId]: newItems }; + }); + }, []); + + // 반복 섹션 아이템 추가 + const handleAddRepeatItem = useCallback( + (sectionId: string) => { + const section = config.sections.find((s) => s.id === sectionId); + if (!section) return; + + const maxItems = section.repeatConfig?.maxItems || 10; + + setRepeatSections((prev) => { + const items = prev[sectionId] || []; + if (items.length >= maxItems) { + toast.error(`최대 ${maxItems}개까지만 추가할 수 있습니다.`); + return prev; + } + + const newItem = createRepeatItem(section, items.length); + return { ...prev, [sectionId]: [...items, newItem] }; + }); + }, + [config], + ); + + // 반복 섹션 아이템 삭제 + const handleRemoveRepeatItem = useCallback( + (sectionId: string, itemId: string) => { + const section = config.sections.find((s) => s.id === sectionId); + if (!section) return; + + const minItems = section.repeatConfig?.minItems || 0; + + setRepeatSections((prev) => { + const items = prev[sectionId] || []; + if (items.length <= minItems) { + toast.error(`최소 ${minItems}개는 유지해야 합니다.`); + return prev; + } + + const newItems = items.filter((item) => item._id !== itemId).map((item, index) => ({ ...item, _index: index })); + + return { ...prev, [sectionId]: newItems }; + }); + + setDeleteDialog({ open: false, sectionId: "", itemId: "" }); + }, + [config], + ); + + // 섹션 접힘 토글 + const toggleSectionCollapse = useCallback((sectionId: string) => { + setCollapsedSections((prev) => { + const newSet = new Set(prev); + if (newSet.has(sectionId)) { + newSet.delete(sectionId); + } else { + newSet.add(sectionId); + } + return newSet; + }); + }, []); + + // Select 옵션 로드 + const loadSelectOptions = useCallback( + async (fieldId: string, optionConfig: SelectOptionConfig): Promise<{ value: string; label: string }[]> => { + // 캐시 확인 + if (selectOptionsCache[fieldId]) { + return selectOptionsCache[fieldId]; + } + + let options: { value: string; label: string }[] = []; + + try { + if (optionConfig.type === "static") { + options = optionConfig.staticOptions || []; + } else if (optionConfig.type === "table" && optionConfig.tableName) { + const response = await apiClient.get(`/table-management/tables/${optionConfig.tableName}/data`, { + params: { limit: 1000 }, + }); + if (response.data?.success && response.data?.data) { + options = response.data.data.map((row: any) => ({ + value: String(row[optionConfig.valueColumn || "id"]), + label: String(row[optionConfig.labelColumn || "name"]), + })); + } + } else if (optionConfig.type === "code" && optionConfig.codeCategory) { + const response = await apiClient.get(`/common-code/${optionConfig.codeCategory}`); + if (response.data?.success && response.data?.data) { + options = response.data.data.map((code: any) => ({ + value: code.code_value || code.codeValue, + label: code.code_name || code.codeName, + })); + } + } + + // 캐시 저장 + setSelectOptionsCache((prev) => ({ ...prev, [fieldId]: options })); + } catch (error) { + console.error(`Select 옵션 로드 실패 (${fieldId}):`, error); + } + + return options; + }, + [selectOptionsCache], + ); + + // 저장 처리 + const handleSave = useCallback(async () => { + if (!config.saveConfig.tableName) { + toast.error("저장할 테이블이 설정되지 않았습니다."); + return; + } + + setSaving(true); + + try { + const { multiRowSave } = config.saveConfig; + + if (multiRowSave?.enabled) { + // 다중 행 저장 + await saveMultipleRows(); + } else { + // 단일 행 저장 + await saveSingleRow(); + } + + // 저장 후 동작 + if (config.saveConfig.afterSave?.showToast) { + toast.success("저장되었습니다."); + } + + if (config.saveConfig.afterSave?.refreshParent) { + window.dispatchEvent(new CustomEvent("refreshParentData")); + } + + onSave?.(formData); + } catch (error: any) { + console.error("저장 실패:", error); + toast.error(error.message || "저장에 실패했습니다."); + } finally { + setSaving(false); + } + }, [config, formData, repeatSections, onSave]); + + // 단일 행 저장 + const saveSingleRow = async () => { + const dataToSave = { ...formData }; + + // 메타데이터 필드 제거 + Object.keys(dataToSave).forEach((key) => { + if (key.startsWith("_")) { + delete dataToSave[key]; + } + }); + + // 저장 시점 채번규칙 처리 + for (const section of config.sections) { + for (const field of section.fields) { + if ( + field.numberingRule?.enabled && + field.numberingRule?.generateOnSave && + field.numberingRule?.ruleId && + !dataToSave[field.columnName] + ) { + const response = await generateNumberingCode(field.numberingRule.ruleId); + if (response.success && response.data?.generatedCode) { + dataToSave[field.columnName] = response.data.generatedCode; + } + } + } + } + + const response = await apiClient.post(`/table-management/tables/${config.saveConfig.tableName}/add`, dataToSave); + + if (!response.data?.success) { + throw new Error(response.data?.message || "저장 실패"); + } + }; + + // 다중 행 저장 (겸직 등) + const saveMultipleRows = async () => { + const { multiRowSave } = config.saveConfig; + if (!multiRowSave) return; + + const { commonFields = [], repeatSectionId = "", typeColumn, mainTypeValue, subTypeValue, mainSectionFields } = + multiRowSave; + + // 공통 필드 데이터 추출 + const commonData: Record = {}; + for (const fieldName of commonFields) { + if (formData[fieldName] !== undefined) { + commonData[fieldName] = formData[fieldName]; + } + } + + // 메인 섹션 필드 데이터 추출 + const mainSectionData: Record = {}; + if (mainSectionFields) { + for (const fieldName of mainSectionFields) { + if (formData[fieldName] !== undefined) { + mainSectionData[fieldName] = formData[fieldName]; + } + } + } + + // 저장할 행들 준비 + const rowsToSave: Record[] = []; + + // 1. 메인 행 생성 + const mainRow: Record = { + ...commonData, + ...mainSectionData, + }; + if (typeColumn) { + mainRow[typeColumn] = mainTypeValue || "main"; + } + rowsToSave.push(mainRow); + + // 2. 반복 섹션 행들 생성 (겸직 등) + const repeatItems = repeatSections[repeatSectionId] || []; + for (const item of repeatItems) { + const subRow: Record = { ...commonData }; + + // 반복 섹션 필드 복사 + Object.keys(item).forEach((key) => { + if (!key.startsWith("_")) { + subRow[key] = item[key]; + } + }); + + if (typeColumn) { + subRow[typeColumn] = subTypeValue || "concurrent"; + } + + rowsToSave.push(subRow); + } + + // 저장 시점 채번규칙 처리 (메인 행만) + for (const section of config.sections) { + if (section.repeatable) continue; + + for (const field of section.fields) { + if (field.numberingRule?.enabled && field.numberingRule?.generateOnSave && field.numberingRule?.ruleId) { + const response = await generateNumberingCode(field.numberingRule.ruleId); + if (response.success && response.data?.generatedCode) { + // 모든 행에 동일한 채번 값 적용 (공통 필드인 경우) + if (commonFields.includes(field.columnName)) { + rowsToSave.forEach((row) => { + row[field.columnName] = response.data?.generatedCode; + }); + } else { + rowsToSave[0][field.columnName] = response.data?.generatedCode; + } + } + } + } + } + + // 모든 행 저장 + for (const row of rowsToSave) { + const response = await apiClient.post(`/table-management/tables/${config.saveConfig.tableName}/add`, row); + + if (!response.data?.success) { + throw new Error(response.data?.message || "저장 실패"); + } + } + + console.log(`[UniversalFormModal] ${rowsToSave.length}개 행 저장 완료`); + }; + + // 폼 초기화 + const handleReset = useCallback(() => { + initializeForm(); + toast.info("폼이 초기화되었습니다."); + }, [initializeForm]); + + // 필드 렌더링 + const renderField = (field: FormFieldConfig, value: any, onChangeHandler: (value: any) => void, fieldKey: string) => { + const isDisabled = field.disabled || (field.numberingRule?.enabled && !field.numberingRule?.editable); + const isHidden = field.numberingRule?.hidden; + + if (isHidden) { + return null; + } + + const fieldElement = (() => { + switch (field.fieldType) { + case "textarea": + return ( +