/** * 품목기준관리 API에서 폼 구조를 로드하는 훅 * * - init API에서 페이지 목록 조회 * - 품목 유형(itemType)에 해당하는 페이지 찾기 * - 해당 페이지의 전체 구조(섹션, 필드) 로드 */ 'use client'; import { useState, useEffect, useCallback } from 'react'; import { itemMasterApi } from '@/lib/api/item-master'; import type { DynamicFormStructure, UseFormStructureResult, SimpleUnitOption, } from '../types'; import { convertToFormStructure } from '../types'; export function useFormStructure( itemType: 'FG' | 'PT' | 'SM' | 'RM' | 'CS' ): UseFormStructureResult { const [structure, setStructure] = useState(null); const [unitOptions, setUnitOptions] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const loadStructure = useCallback(async () => { setIsLoading(true); setError(null); try { // 1. init API에서 전체 데이터 로드 const initData = await itemMasterApi.init(); // 단위 옵션 저장 (SimpleUnitOption 형식으로 변환) console.log('[useFormStructure] API initData.unitOptions:', initData.unitOptions); const simpleUnitOptions: SimpleUnitOption[] = (initData.unitOptions || []).map((u) => ({ label: u.label, value: u.value, })); console.log('[useFormStructure] Processed unitOptions:', simpleUnitOptions.length, 'items'); setUnitOptions(simpleUnitOptions); // 2. 품목 유형에 해당하는 페이지 찾기 const page = initData.pages.find((p) => p.item_type === itemType); if (!page) { // 페이지가 없으면 빈 구조 반환 (품목기준관리에서 아직 설정 안된 경우) setStructure({ page: { id: 0, tenant_id: 0, page_name: `${itemType} 기본 페이지`, item_type: itemType, description: null, absolute_path: null, is_active: true, order_no: 0, created_by: null, updated_by: null, created_at: '', updated_at: '', }, sections: [], directFields: [], }); return; } // 3. 페이지 전체 구조 로드 const pageStructure = await itemMasterApi.pages.getStructure(page.id); const formStructure = convertToFormStructure(pageStructure); setStructure(formStructure); } catch (err) { console.error('품목 폼 구조 로드 실패:', err); setError(err instanceof Error ? err.message : '폼 구조를 불러올 수 없습니다.'); } finally { setIsLoading(false); } }, [itemType]); useEffect(() => { loadStructure(); }, [loadStructure]); return { structure, isLoading, error, unitOptions, refetch: loadStructure, }; }