'use client' /** * 국가 선택기 * * @description * - 오라클에서 CMCTB_CD 테이블에 대해, CD_CLF = 'LE0010' 인 건들을 조회 * - CD 컬럼이 대문자 알파벳 2글자 국가코드 * - CD2 컬럼이 대문자 알파벳 3글자 국가코드 * - CD3 컬럼이 3글자 숫자로 표현되는 국가코드 (0으로 시작할 수 있음) * - CDNM 컬럼이 한국어 국가명 * - GRP_DSC 컬럼이 영문 국가명 */ import { useState, useCallback, useMemo, useTransition } from 'react' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Search, Check } from 'lucide-react' import { ColumnDef, flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, useReactTable, SortingState, ColumnFiltersState, VisibilityState, RowSelectionState, } from '@tanstack/react-table' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/components/ui/table' import { getNationCodes, NationCode, NationSearchOptions } from './nation-service' import { toast } from 'sonner' // 간단한 디바운스 함수 function debounce void>(func: T, delay: number): T { let timeoutId: NodeJS.Timeout return ((...args: Parameters) => { clearTimeout(timeoutId) timeoutId = setTimeout(() => func(...args), delay) }) as T } export interface NationSelectorProps { selectedNation?: NationCode onNationSelect: (nation: NationCode) => void disabled?: boolean searchOptions?: Partial placeholder?: string className?: string } export function NationSelector({ selectedNation, onNationSelect, disabled, searchOptions = {}, placeholder = "국가를 선택하세요", className }: NationSelectorProps) { const [open, setOpen] = useState(false) const [nations, setNations] = useState([]) const [sorting, setSorting] = useState([]) const [columnFilters, setColumnFilters] = useState([]) const [columnVisibility, setColumnVisibility] = useState({}) const [rowSelection, setRowSelection] = useState({}) const [globalFilter, setGlobalFilter] = useState('') const [isPending, startTransition] = useTransition() // searchOptions 안정화 const stableSearchOptions = useMemo(() => ({ limit: 100, ...searchOptions }), [searchOptions]) // 국가 선택 핸들러 const handleNationSelect = useCallback((nation: NationCode) => { onNationSelect(nation) setOpen(false) }, [onNationSelect]) // 테이블 컬럼 정의 const columns: ColumnDef[] = useMemo(() => [ { accessorKey: 'CD', header: '2글자코드', cell: ({ row }) => (
{row.getValue('CD')}
), }, { accessorKey: 'CD2', header: '3글자코드', cell: ({ row }) => (
{row.getValue('CD2')}
), }, { accessorKey: 'CD3', header: '숫자코드', cell: ({ row }) => (
{row.getValue('CD3')}
), }, { accessorKey: 'CDNM', header: '한국어명', cell: ({ row }) => (
{row.getValue('CDNM')}
), }, { accessorKey: 'GRP_DSC', header: '영문명', cell: ({ row }) => (
{row.getValue('GRP_DSC')}
), }, { id: 'actions', header: '선택', cell: ({ row }) => ( ), }, ], [handleNationSelect]) // 국가 테이블 설정 const table = useReactTable({ data: nations, columns, onSortingChange: setSorting, onColumnFiltersChange: setColumnFilters, onColumnVisibilityChange: setColumnVisibility, onRowSelectionChange: setRowSelection, onGlobalFilterChange: setGlobalFilter, getCoreRowModel: getCoreRowModel(), getPaginationRowModel: getPaginationRowModel(), getSortedRowModel: getSortedRowModel(), getFilteredRowModel: getFilteredRowModel(), state: { sorting, columnFilters, columnVisibility, rowSelection, globalFilter, }, }) // 서버 액션을 사용한 국가 목록 로드 const loadNations = useCallback(async (searchTerm?: string) => { startTransition(async () => { try { const result = await getNationCodes({ ...stableSearchOptions, searchTerm: searchTerm }) if (result.success) { setNations(result.data) } else { toast.error(result.error || '국가코드를 불러오는데 실패했습니다.') setNations([]) } } catch (error) { console.error('국가코드 목록 로드 실패:', error) toast.error('국가코드를 불러오는 중 오류가 발생했습니다.') setNations([]) } }) }, [stableSearchOptions]) // 디바운스된 검색 (클라이언트 로직만) const debouncedSearch = useMemo( () => debounce((searchTerm: string) => { loadNations(searchTerm) }, 300), [loadNations] ) // 다이얼로그 열기 핸들러 const handleDialogOpenChange = useCallback((newOpen: boolean) => { setOpen(newOpen) if (newOpen && nations.length === 0) { loadNations() } }, [loadNations, nations.length]) // 검색어 변경 핸들러 const handleSearchChange = useCallback((value: string) => { setGlobalFilter(value) if (open) { debouncedSearch(value) } }, [open, debouncedSearch]) return ( 국가 선택
국가코드(CD_CLF=LE0010) 조회
handleSearchChange(e.target.value)} className="flex-1" />
{isPending ? (
국가코드를 불러오는 중...
) : (
{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => ( {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} ))} ))} {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( handleNationSelect(row.original)} > {row.getVisibleCells().map((cell) => ( {flexRender( cell.column.columnDef.cell, cell.getContext() )} ))} )) ) : ( 검색 결과가 없습니다. )}
)}
총 {table.getFilteredRowModel().rows.length}개 국가
{table.getState().pagination.pageIndex + 1} / {table.getPageCount()}
) }