251201_01_ENH : datatable, autocomplete, user관리 완성
This commit is contained in:
138
src/components/common/KriAutoComplete.tsx
Normal file
138
src/components/common/KriAutoComplete.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MultiSelect } from '@/components/ui/multi-select'
|
||||
import type { MultiSelectOption } from '@/components/ui/multi-select'
|
||||
|
||||
type BaseProps<T> = {
|
||||
items: T[]
|
||||
searchable?: boolean
|
||||
searchMode?: "filter" | "inputOnly";
|
||||
onSearchValueChange?: (value: string) => void;
|
||||
placeholder?: string
|
||||
widthClassName?: string
|
||||
heightClassName?: string
|
||||
className?: string
|
||||
getValue?: (item: T) => string
|
||||
getLabel?: (item: T) => string
|
||||
}
|
||||
|
||||
type KriMultiSelectProps<T> = BaseProps<T> & {
|
||||
value: string[]
|
||||
onChange: (value: string[]) => void
|
||||
/** 최대 선택 개수 제한 (없으면 무제한) */
|
||||
maxCount?: number
|
||||
maxSelected?: number
|
||||
hideSelectAll?: boolean
|
||||
}
|
||||
|
||||
export function KriMultiSelect<T>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
onSearchValueChange,
|
||||
maxCount = 1,
|
||||
maxSelected,
|
||||
hideSelectAll = false,
|
||||
placeholder = 'Select options',
|
||||
widthClassName,
|
||||
heightClassName,
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
}: KriMultiSelectProps<T>) {
|
||||
const extractValue = React.useCallback((item: T) => (getValue ? getValue(item) : String(item)), [getValue])
|
||||
const extractLabel = React.useCallback((item: T) => (getLabel ? getLabel(item) : String(item)), [getLabel])
|
||||
|
||||
const options = React.useMemo<MultiSelectOption[]>(
|
||||
() =>
|
||||
items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
})),
|
||||
[items, extractValue, extractLabel]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect
|
||||
options={options}
|
||||
defaultValue={value}
|
||||
onValueChange={onChange}
|
||||
maxSelected={maxSelected}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white content-text-lg", className)}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
maxCount={maxCount}
|
||||
hideSelectAll={hideSelectAll}
|
||||
autoSize
|
||||
singleLine
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type KriSingleSelectProps<T> = BaseProps<T> & {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
export function KriSingleSelect<T>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
searchable = true,
|
||||
searchMode = "filter",
|
||||
onSearchValueChange,
|
||||
placeholder = 'Select an option',
|
||||
heightClassName,
|
||||
widthClassName,
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
}: KriSingleSelectProps<T>) {
|
||||
const extractValue = React.useCallback((item: T) => (getValue ? getValue(item) : String(item)), [getValue])
|
||||
const extractLabel = React.useCallback((item: T) => (getLabel ? getLabel(item) : String(item)), [getLabel])
|
||||
|
||||
const options = React.useMemo<MultiSelectOption[]>(
|
||||
() =>
|
||||
items.map((item) => ({
|
||||
value: extractValue(item),
|
||||
label: extractLabel(item),
|
||||
})),
|
||||
[items, extractValue, extractLabel]
|
||||
)
|
||||
|
||||
const defaultValue = React.useMemo(() => (value ? [value] : []), [value]);
|
||||
|
||||
return (
|
||||
<div className={cn(widthClassName, heightClassName, "flex-none overflow-hidden")}>
|
||||
<MultiSelect
|
||||
options={options}
|
||||
defaultValue={defaultValue}
|
||||
onValueChange={(next) => onChange(next.at(-1) ?? '')}
|
||||
selectionMode="single"
|
||||
maxCount={1}
|
||||
maxSelected={1}
|
||||
placeholder={placeholder}
|
||||
className={cn("bg-white content-text-lg", className)}
|
||||
searchable={searchable}
|
||||
searchMode={searchMode}
|
||||
onSearchValueChange={onSearchValueChange}
|
||||
hideSelectAll
|
||||
autoSize
|
||||
singleLine
|
||||
closeOnSelect
|
||||
resetOnDefaultValueChange
|
||||
deduplicateOptions
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
196
src/components/common/KriPassword.tsx
Normal file
196
src/components/common/KriPassword.tsx
Normal file
@@ -0,0 +1,196 @@
|
||||
'use client'
|
||||
|
||||
import { useId, useMemo, useState } from 'react'
|
||||
import { CheckIcon, EyeIcon, EyeOffIcon, XIcon } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// ✅ 화면에 보여줄 “허용 특수문자”
|
||||
export const ALLOWED_SPECIALS_TEXT =
|
||||
`! @ # $ % ^ & * ( ) _ + - = { } [ ] : ; " ' < > , . ? /`
|
||||
|
||||
// ✅ “허용 문자만” 체크(공백/한글/기타 특수문자 차단)
|
||||
export const ONLY_ALLOWED_REGEX =
|
||||
/^[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]+$/
|
||||
|
||||
// ✅ 최종 비밀번호 규칙(특수문자 필수 아님)
|
||||
// - 8~20자
|
||||
// - 영문 1개 이상 + 숫자 1개 이상
|
||||
// - 구성 문자는 허용 문자만
|
||||
export const KRI_PW_REGEX =
|
||||
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-={}\[\]:;"'<>,.?\/]{8,20}$/
|
||||
|
||||
const requirements = [
|
||||
{ regex: /[A-Za-z]/, text: '영문 1개 이상 (A–Z 또는 a–z)' },
|
||||
{ regex: /\d/, text: '숫자 1개 이상' },
|
||||
{ regex: /^.{10,}$/, text: '10자 이상' },
|
||||
{
|
||||
regex: /[!@#$%^&*()_+\-={}\[\]:;"'<>,.?/]/,
|
||||
text: `특수문자 사용 (허용: ${ALLOWED_SPECIALS_TEXT})`,
|
||||
},
|
||||
]
|
||||
|
||||
type KriPasswordProps = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
id?: string
|
||||
label?: string
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
const KriPassword = ({
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
label = '비밀번호',
|
||||
placeholder = '비밀번호를 입력하세요',
|
||||
disabled,
|
||||
className,
|
||||
}: KriPasswordProps) => {
|
||||
const [isVisible, setIsVisible] = useState(false)
|
||||
|
||||
const autoId = useId()
|
||||
const inputId = id ?? autoId
|
||||
const toggleVisibility = () => setIsVisible((prev) => !prev)
|
||||
const isValid = useMemo(() => KRI_PW_REGEX.test(value), [value])
|
||||
const hasOnlyAllowedChars = useMemo(
|
||||
() => (value ? ONLY_ALLOWED_REGEX.test(value) : true),
|
||||
[value]
|
||||
)
|
||||
|
||||
const checks = useMemo(
|
||||
() =>
|
||||
requirements.map((req) => ({
|
||||
met: req.regex.test(value),
|
||||
text: req.text,
|
||||
})),
|
||||
[value]
|
||||
)
|
||||
|
||||
const statusText = useMemo(() => {
|
||||
if (!value) return '비밀번호를 입력하세요'
|
||||
if (!hasOnlyAllowedChars) return '허용되지 않는 문자가 포함되어 있어요'
|
||||
return isValid ? '사용 가능한 비밀번호입니다' : '비밀번호 규칙을 만족하지 않아요'
|
||||
}, [value, isValid, hasOnlyAllowedChars])
|
||||
|
||||
const score = useMemo(() => checks.filter((c) => c.met).length, [checks])
|
||||
|
||||
const getBarColor = (s: number) => {
|
||||
if (s === 0) return 'bg-border'
|
||||
if (s === 1) return 'bg-destructive'
|
||||
if (s === 2) return 'bg-orange-500'
|
||||
if (s === 3) return 'bg-yellow-400'
|
||||
return 'bg-green-500' // 4
|
||||
}
|
||||
|
||||
const getStrengthText = (s: number) => {
|
||||
if (s === 0) return '비밀번호를 입력하세요'
|
||||
if (s === 1) return '약함'
|
||||
if (s === 2) return '보통'
|
||||
if (s === 3) return '강함'
|
||||
return '매우 강함'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('w-full space-y-2', className)}>
|
||||
<Label htmlFor={inputId}>{label}</Label>
|
||||
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={inputId}
|
||||
type={isVisible ? 'text' : 'password'}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="pr-9"
|
||||
disabled={disabled}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleVisibility}
|
||||
disabled={disabled}
|
||||
className="text-muted-foreground focus-visible:ring-ring/50 absolute inset-y-0 right-0 rounded-l-none hover:bg-transparent"
|
||||
>
|
||||
{isVisible ? <EyeOffIcon /> : <EyeIcon />}
|
||||
<span className="sr-only">{isVisible ? '숨기기' : '보기'}</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Strength bars */}
|
||||
<div className="flex h-1 w-full gap-1">
|
||||
{Array.from({ length: requirements.length }).map((_, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className={cn(
|
||||
'h-full flex-1 rounded-full transition-all duration-300 ease-out',
|
||||
index < score ? getBarColor(score) : 'bg-border'
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
{value ? (
|
||||
isValid ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-destructive" />
|
||||
)
|
||||
) : (
|
||||
<span className="mt-0.5 size-4" />
|
||||
)}
|
||||
|
||||
<p
|
||||
className={cn(
|
||||
'text-xs',
|
||||
!value
|
||||
? 'text-muted-foreground'
|
||||
: isValid
|
||||
? 'text-green-600 dark:text-green-400'
|
||||
: 'text-destructive'
|
||||
)}
|
||||
>
|
||||
{statusText}
|
||||
</p>
|
||||
</div>
|
||||
{
|
||||
/*
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
{getStrengthText(score)}.
|
||||
</p>
|
||||
<p className="text-foreground text-sm font-medium">
|
||||
포함 조건:
|
||||
</p>
|
||||
<ul className="space-y-1.5">
|
||||
{checks.map((c, idx) => (
|
||||
<li key={idx} className="flex items-start gap-2">
|
||||
{c.met ? (
|
||||
<CheckIcon className="mt-0.5 size-4 text-green-600 dark:text-green-400" />
|
||||
) : (
|
||||
<XIcon className="mt-0.5 size-4 text-muted-foreground" />
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs',
|
||||
c.met ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{c.text}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
*/
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KriPassword
|
||||
74
src/components/common/KriSelect.tsx
Normal file
74
src/components/common/KriSelect.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
'use client'
|
||||
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type KriSelectItem = {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
type KriSelectProps<T> = {
|
||||
/** options 배열: string[] 혹은 T[] */
|
||||
items: T[]
|
||||
/** 현재 선택 값 */
|
||||
value: string
|
||||
/** 값 변경 시 호출 */
|
||||
onChange: (value: string) => void
|
||||
/** placeholder 텍스트 */
|
||||
placeholder?: string
|
||||
/** 기타 클래스 (예: 'w-40') */
|
||||
className?: string
|
||||
/** value를 어떻게 뽑을지 (없으면 String(item)) */
|
||||
getValue?: (item: T) => string
|
||||
/** label을 어떻게 뽑을지 (없으면 String(item)) */
|
||||
getLabel?: (item: T) => string
|
||||
/** 전체 사용 여부 */
|
||||
useAll?: boolean
|
||||
}
|
||||
|
||||
export function KriSelect<T>({
|
||||
items,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
className,
|
||||
getValue,
|
||||
getLabel,
|
||||
useAll = true,
|
||||
}: KriSelectProps<T>) {
|
||||
const extractValue = (item: T) =>
|
||||
getValue ? getValue(item) : String(item)
|
||||
|
||||
const extractLabel = (item: T) =>
|
||||
getLabel ? getLabel(item) : String(item)
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={value}
|
||||
onValueChange={onChange}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
'w-fit whitespace-nowrap bg-white content-text-lg', // 폰트 사이즈
|
||||
className
|
||||
)}
|
||||
aria-label={placeholder ?? 'select'}
|
||||
>
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ useAll? <SelectItem key="ALL" value="ALL">전체</SelectItem> :null }
|
||||
{items.map((item, idx) => {
|
||||
const v = extractValue(item)
|
||||
const label = extractLabel(item)
|
||||
return (
|
||||
<SelectItem key={v ?? idx} value={v}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
)
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
366
src/components/data-table/DataTable.tsx
Normal file
366
src/components/data-table/DataTable.tsx
Normal file
@@ -0,0 +1,366 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
ChevronsLeftIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronsRightIcon,
|
||||
ArrowUp,
|
||||
ArrowDown,
|
||||
ArrowUpDown
|
||||
} from 'lucide-react'
|
||||
|
||||
import type { PaginationState, SortingState, RowSelectionState } from '@tanstack/react-table'
|
||||
import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable
|
||||
} from '@tanstack/react-table'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from '@/components/ui/pagination'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
|
||||
import { usePagination } from './hooks/usePagination'
|
||||
import { DataTableProps, DataTableColumn } from './DataTable.type'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function DataTable<TData>({
|
||||
columns,
|
||||
data,
|
||||
getRowId,
|
||||
highlightRowIds,
|
||||
isClient = true,
|
||||
pageCount: serverPageCount,
|
||||
totalCount: serverTotalCount,
|
||||
onPaginationChange: onServerPaginationChange,
|
||||
onSortingChange: onServerSortingChange,
|
||||
selectMode = 'none',
|
||||
onRowSelectionChange,
|
||||
enableRowClickSelection = false,
|
||||
defaultPageSize = 10,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
paginationItemsToDisplay = 5
|
||||
}: DataTableProps<TData>) {
|
||||
// Pagination state
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: defaultPageSize
|
||||
})
|
||||
|
||||
// Sorting state
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
|
||||
// Row selection state
|
||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
|
||||
|
||||
// 서버 페이지네이션일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerPaginationChange) {
|
||||
onServerPaginationChange(pagination)
|
||||
}
|
||||
}, [pagination, isClient, onServerPaginationChange])
|
||||
|
||||
// 서버 정렬일 때 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (!isClient && onServerSortingChange) {
|
||||
onServerSortingChange(sorting)
|
||||
}
|
||||
}, [sorting, isClient, onServerSortingChange])
|
||||
|
||||
// Row selection 변경 시 부모에게 알림
|
||||
useEffect(() => {
|
||||
if (selectMode !== 'none' && onRowSelectionChange) {
|
||||
const selectedRows = table
|
||||
.getSelectedRowModel()
|
||||
.rows.map(row => row.original)
|
||||
onRowSelectionChange(selectedRows)
|
||||
}
|
||||
}, [rowSelection, selectMode])
|
||||
|
||||
// selectMode에 따라 select column 추가
|
||||
const enhancedColumns: DataTableColumn<TData, any>[] = [
|
||||
...(selectMode !== 'none'
|
||||
? [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) =>
|
||||
selectMode === 'multi' ? (
|
||||
<Checkbox
|
||||
checked={
|
||||
table.getIsAllPageRowsSelected() ||
|
||||
(table.getIsSomePageRowsSelected() && 'indeterminate')
|
||||
}
|
||||
onCheckedChange={value => table.toggleAllPageRowsSelected(!!value)}
|
||||
aria-label='KriSelect all'
|
||||
/>
|
||||
) : null,
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
checked={row.getIsSelected()}
|
||||
onCheckedChange={value => {
|
||||
if (selectMode === 'single') {
|
||||
// single mode: 다른 것 모두 해제
|
||||
table.resetRowSelection()
|
||||
}
|
||||
row.toggleSelected(!!value)
|
||||
}}
|
||||
aria-label='KriSelect row'
|
||||
onClick={e => e.stopPropagation()} // row 클릭 이벤트 전파 방지
|
||||
/>
|
||||
),
|
||||
size: 28,
|
||||
enableSorting: false
|
||||
} as DataTableColumn<TData, any>
|
||||
]
|
||||
: []),
|
||||
...columns
|
||||
]
|
||||
|
||||
// Row 클릭 핸들러
|
||||
const handleRowClick = (row: any) => {
|
||||
if (!enableRowClickSelection || selectMode === 'none') return
|
||||
|
||||
if (selectMode === 'single') {
|
||||
table.resetRowSelection()
|
||||
row.toggleSelected(true)
|
||||
} else {
|
||||
row.toggleSelected(!row.getIsSelected())
|
||||
}
|
||||
}
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns: enhancedColumns,
|
||||
pageCount: isClient ? undefined : serverPageCount,
|
||||
state: {
|
||||
sorting,
|
||||
pagination,
|
||||
rowSelection
|
||||
},
|
||||
enableRowSelection: selectMode !== 'none',
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onPaginationChange: setPagination,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: isClient ? getSortedRowModel() : undefined,
|
||||
getPaginationRowModel: isClient ? getPaginationRowModel() : undefined,
|
||||
manualPagination: !isClient,
|
||||
manualSorting: !isClient,
|
||||
enableSortingRemoval: false,
|
||||
...(getRowId && { getRowId }), //있으면만 적용
|
||||
})
|
||||
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = usePagination({
|
||||
currentPage: table.getState().pagination.pageIndex + 1,
|
||||
totalPages: table.getPageCount(),
|
||||
paginationItemsToDisplay
|
||||
})
|
||||
|
||||
const totalCount = isClient ? data.length : (serverTotalCount || 0)
|
||||
|
||||
return (
|
||||
<div className='w-full space-y-4'>
|
||||
<div className='rounded-md border'>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<TableRow key={headerGroup.id} className='hover:bg-transparent'>
|
||||
{headerGroup.headers.map(header => {
|
||||
const column = header.column
|
||||
const canSort = column.getCanSort()
|
||||
const sorted = column.getIsSorted() as false | 'asc' | 'desc'
|
||||
const headerContent = header.isPlaceholder
|
||||
? null
|
||||
: flexRender(column.columnDef.header, header.getContext())
|
||||
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn(
|
||||
'content-text-lg font-semibold text-gray-900',
|
||||
column.id === 'actions' && 'w-[140px] text-center'
|
||||
)}
|
||||
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
|
||||
>
|
||||
{header.isPlaceholder ? null : canSort ? (
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
className='px-0 font-semibold content-text-lg flex items-center gap-1'
|
||||
onClick={column.getToggleSortingHandler()}
|
||||
>
|
||||
<span>{headerContent}</span>
|
||||
{sorted === 'asc' && <ArrowUp className='w-3 h-3' />}
|
||||
{sorted === 'desc' && <ArrowDown className='w-3 h-3' />}
|
||||
{!sorted && <ArrowUpDown className='w-3 h-3 text-muted-foreground' />}
|
||||
</Button>
|
||||
) : (
|
||||
headerContent
|
||||
)}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map(row => {
|
||||
const shouldHighlight = highlightRowIds && highlightRowIds.includes(row.id)
|
||||
return (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && 'selected'}
|
||||
onClick={() => handleRowClick(row)}
|
||||
className={cn(
|
||||
'content-text-base',
|
||||
'[&>td]:py-0 [&>td]:px-2',
|
||||
enableRowClickSelection && selectMode !== 'none' && 'cursor-pointer',
|
||||
'data-[state=selected]:bg-slate-100 data-[state=selected]:font-semibold',
|
||||
shouldHighlight && 'bg-emerald-50',
|
||||
)}
|
||||
>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)})
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={enhancedColumns.length} className='h-24 text-center'>
|
||||
데이터가 없습니다.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
<div className='flex items-center justify-between gap-3 max-sm:flex-col p-2 pt-0'>
|
||||
<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>
|
||||
Page <span className='text-foreground'>{table.getState().pagination.pageIndex + 1}</span> of{' '}
|
||||
<span className='text-foreground'>{table.getPageCount()}</span>
|
||||
{!isClient && totalCount > 0 && (
|
||||
<span className='ml-2'>
|
||||
(총 <span className='text-foreground'>{totalCount}</span>건)
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className='grow'>
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.firstPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
aria-label='Go to first page'
|
||||
>
|
||||
<ChevronsLeftIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.previousPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
aria-label='Go to previous page'
|
||||
>
|
||||
<ChevronLeftIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
|
||||
{showLeftEllipsis && (
|
||||
<PaginationItem>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
)}
|
||||
|
||||
{pages.map(page => {
|
||||
const isActive = page === table.getState().pagination.pageIndex + 1
|
||||
|
||||
return (
|
||||
<PaginationItem key={page}>
|
||||
<Button
|
||||
size='icon'
|
||||
variant={isActive ? 'default' : 'ghost'}
|
||||
onClick={() => table.setPageIndex(page - 1)}
|
||||
aria-current={isActive ? 'page' : undefined}
|
||||
>
|
||||
{page}
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
)
|
||||
})}
|
||||
|
||||
{showRightEllipsis && (
|
||||
<PaginationItem>
|
||||
<PaginationEllipsis />
|
||||
</PaginationItem>
|
||||
)}
|
||||
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.nextPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
aria-label='Go to next page'
|
||||
>
|
||||
<ChevronRightIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
size='icon'
|
||||
variant='outline'
|
||||
className='disabled:pointer-events-none disabled:opacity-50'
|
||||
onClick={() => table.lastPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
aria-label='Go to last page'
|
||||
>
|
||||
<ChevronsRightIcon aria-hidden='true' />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-1 justify-end'>
|
||||
<Select
|
||||
value={table.getState().pagination.pageSize.toString()}
|
||||
onValueChange={value => {
|
||||
table.setPageSize(Number(value))
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id='results-per-page' className='w-fit whitespace-nowrap' aria-label='Results per page'>
|
||||
<SelectValue placeholder='페이지당 개수' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pageSizeOptions.map(size => (
|
||||
<SelectItem key={size} value={size.toString()}>
|
||||
{size} / page
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
47
src/components/data-table/DataTable.type.ts
Normal file
47
src/components/data-table/DataTable.type.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
|
||||
|
||||
export type SelectMode = 'none' | 'single' | 'multi'
|
||||
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> & {
|
||||
enableSorting?: boolean // 정렬 가능 여부 (기본값: false)
|
||||
}
|
||||
|
||||
export interface ServerPaginationParams {
|
||||
pageIndex: number
|
||||
pageSize: number
|
||||
sorting?: SortingState
|
||||
}
|
||||
|
||||
export interface ServerPaginationResponse<TData> {
|
||||
data: TData[]
|
||||
totalCount: number
|
||||
pageCount: number
|
||||
}
|
||||
|
||||
export interface DataTableProps<TData> {
|
||||
// 필수 props
|
||||
columns: DataTableColumn<TData, any>[]
|
||||
data: TData[]
|
||||
getRowId?: (row: TData, index: number) => string //id 지정
|
||||
highlightRowIds?: string[]
|
||||
// 페이지네이션 모드
|
||||
isClient?: boolean // true: 클라이언트, false: 서버 (기본값: true)
|
||||
|
||||
// 서버 페이지네이션 (isClient=false일 때 필요)
|
||||
pageCount?: number
|
||||
totalCount?: number
|
||||
onPaginationChange?: (pagination: PaginationState) => void
|
||||
onSortingChange?: (sorting: SortingState) => void
|
||||
|
||||
// 선택 모드
|
||||
selectMode?: SelectMode // 'none' | 'single' | 'multi' (기본값: 'none')
|
||||
onRowSelectionChange?: (selectedRows: TData[]) => void
|
||||
enableRowClickSelection?: boolean // row 클릭 시 select 여부 (기본값: false)
|
||||
|
||||
// 페이지네이션 설정
|
||||
defaultPageSize?: number
|
||||
pageSizeOptions?: number[]
|
||||
|
||||
// 기타 설정
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
38
src/components/data-table/hooks/usePagination.ts
Normal file
38
src/components/data-table/hooks/usePagination.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useMemo } from 'react'
|
||||
|
||||
interface UsePaginationProps {
|
||||
currentPage: number
|
||||
totalPages: number
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
|
||||
export function usePagination({
|
||||
currentPage,
|
||||
totalPages,
|
||||
paginationItemsToDisplay = 5
|
||||
}: UsePaginationProps) {
|
||||
const { pages, showLeftEllipsis, showRightEllipsis } = useMemo(() => {
|
||||
const halfDisplay = Math.floor(paginationItemsToDisplay / 2)
|
||||
|
||||
let startPage = Math.max(1, currentPage - halfDisplay)
|
||||
let endPage = Math.min(totalPages, currentPage + halfDisplay)
|
||||
|
||||
if (currentPage <= halfDisplay) {
|
||||
endPage = Math.min(paginationItemsToDisplay, totalPages)
|
||||
}
|
||||
|
||||
if (currentPage > totalPages - halfDisplay) {
|
||||
startPage = Math.max(1, totalPages - paginationItemsToDisplay + 1)
|
||||
}
|
||||
|
||||
const pages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i)
|
||||
|
||||
return {
|
||||
pages,
|
||||
showLeftEllipsis: startPage > 1,
|
||||
showRightEllipsis: endPage < totalPages
|
||||
}
|
||||
}, [currentPage, totalPages, paginationItemsToDisplay])
|
||||
|
||||
return { pages, showLeftEllipsis, showRightEllipsis }
|
||||
}
|
||||
333
src/components/dialog/ListUploadDialog.tsx
Normal file
333
src/components/dialog/ListUploadDialog.tsx
Normal file
@@ -0,0 +1,333 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { useState, useRef } from 'react'
|
||||
import { Upload, X } from 'lucide-react'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
|
||||
export type UploadMode = 'add' | 'replace'
|
||||
export type ValidationOption = {
|
||||
checkEmailDuplicate: boolean
|
||||
checkPhoneDuplicate: boolean
|
||||
}
|
||||
|
||||
export type ListUploadDialogProps = {
|
||||
/** jotai로 관리할 dialog id (기본값: 'listUploadDialog') */
|
||||
dialogId?: DialogId
|
||||
|
||||
/** 필요하면 부모에서 직접 제어도 가능 */
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
|
||||
onUpload: (
|
||||
file: File,
|
||||
mode: UploadMode,
|
||||
validation: ValidationOption,
|
||||
) => void | Promise<void>
|
||||
onDownloadTemplate?: () => void
|
||||
}
|
||||
|
||||
const ListUploadDialog = ({
|
||||
dialogId = 'listUploadDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
onUpload,
|
||||
onDownloadTemplate,
|
||||
}: ListUploadDialogProps) => {
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [uploadMode, setUploadMode] = useState<UploadMode>('add')
|
||||
const [validation, setValidation] = useState<ValidationOption>({
|
||||
checkEmailDuplicate: false,
|
||||
checkPhoneDuplicate: false,
|
||||
})
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// ✅ 실제 Dialog에 넘길 open 값 (props 우선, 없으면 jotai 사용)
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
// ✅ 공통 openChange 처리 (부모 콜백 + jotai 동시 반영)
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
onOpenChange?.(nextOpen)
|
||||
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
} else {
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
}
|
||||
|
||||
const resetState = () => {
|
||||
setSelectedFile(null)
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
setUploadMode('add')
|
||||
setValidation({
|
||||
checkEmailDuplicate: false,
|
||||
checkPhoneDuplicate: false,
|
||||
})
|
||||
}
|
||||
|
||||
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
const allowedTypes = [
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'text/csv',
|
||||
]
|
||||
|
||||
if (
|
||||
allowedTypes.includes(file.type) ||
|
||||
file.name.endsWith('.xlsx') ||
|
||||
file.name.endsWith('.xls') ||
|
||||
file.name.endsWith('.csv')
|
||||
) {
|
||||
setSelectedFile(file)
|
||||
} else {
|
||||
alert('엑셀 파일만 업로드 가능합니다. (.xlsx, .xls, .csv)')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveFile = () => {
|
||||
setSelectedFile(null)
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadClick = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedFile) {
|
||||
alert('파일을 선택해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
setIsUploading(true)
|
||||
try {
|
||||
await onUpload(selectedFile, uploadMode, validation)
|
||||
// 성공 시 초기화 + 닫기
|
||||
resetState()
|
||||
handleOpenChange(false)
|
||||
} catch (error) {
|
||||
console.error('업로드 실패:', error)
|
||||
alert('업로드에 실패했습니다.')
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Dialog의 onOpenChange에 연결되는 최종 핸들러
|
||||
const handleDialogOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen && !isUploading) {
|
||||
resetState()
|
||||
}
|
||||
handleOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-xl font-bold">엑셀 업로드</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
{/* 1. 리스트 업로드 */}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium flex items-center gap-2">
|
||||
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
|
||||
1
|
||||
</span>
|
||||
리스트 업로드
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
className="flex-1 bg-green-600 hover:bg-green-700"
|
||||
onClick={() => {
|
||||
if (onDownloadTemplate) onDownloadTemplate()
|
||||
else alert('양식 다운로드 기능이 아직 구현되지 않았습니다.')
|
||||
}}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
onClick={handleUploadClick}
|
||||
disabled={isUploading}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
{selectedFile ? selectedFile.name : '선택된 파일 없음'}
|
||||
</Button>
|
||||
</div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
{selectedFile && (
|
||||
<div className="flex items-center justify-between p-3 bg-blue-50 rounded-md border border-blue-200">
|
||||
<span className="text-sm text-blue-900 truncate">
|
||||
{selectedFile.name}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleRemoveFile}
|
||||
disabled={isUploading}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 2. Excel 파일 업로드 */}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium flex items-center gap-2">
|
||||
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
|
||||
2
|
||||
</span>
|
||||
Excel 파일 업로드
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{/* 3. 업로드 방식 선택 */}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium flex items-center gap-2">
|
||||
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
|
||||
3
|
||||
</span>
|
||||
업로드 이력
|
||||
</Label>
|
||||
<RadioGroup
|
||||
value={uploadMode}
|
||||
onValueChange={value => setUploadMode(value as UploadMode)}
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="add" id="add" />
|
||||
<Label htmlFor="add" className="font-normal cursor-pointer">
|
||||
추가
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="replace" id="replace" />
|
||||
<Label htmlFor="replace" className="font-normal cursor-pointer">
|
||||
교체
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{/* 4. 중복 검사 옵션 */}
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium flex items-center gap-2">
|
||||
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs">
|
||||
4
|
||||
</span>
|
||||
중복 검사
|
||||
</Label>
|
||||
<div className="space-y-2 pl-8">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="emailCheck"
|
||||
checked={validation.checkEmailDuplicate}
|
||||
onCheckedChange={checked =>
|
||||
setValidation(prev => ({
|
||||
...prev,
|
||||
checkEmailDuplicate: checked === true,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<Label
|
||||
htmlFor="emailCheck"
|
||||
className="font-normal cursor-pointer"
|
||||
>
|
||||
이메일 중복검사
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="phoneCheck"
|
||||
checked={validation.checkPhoneDuplicate}
|
||||
onCheckedChange={checked =>
|
||||
setValidation(prev => ({
|
||||
...prev,
|
||||
checkPhoneDuplicate: checked === true,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<Label
|
||||
htmlFor="phoneCheck"
|
||||
className="font-normal cursor-pointer"
|
||||
>
|
||||
전화번호 중복검사
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 5. 업로드 이력 (드롭다운) */}
|
||||
<div className="space-y-3">
|
||||
<select
|
||||
className="w-full px-3 py-2 border border-input rounded-md text-sm"
|
||||
defaultValue=""
|
||||
>
|
||||
<option value="" disabled>
|
||||
업로드 이력
|
||||
</option>
|
||||
<option>2024-01-15 14:30 - 파일1.xlsx (추가)</option>
|
||||
<option>2024-01-14 10:20 - 파일2.xlsx (교체)</option>
|
||||
</select>
|
||||
<Button type="button" variant="outline" className="w-full">
|
||||
다운로드
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<div className="flex items-center justify-end w-full gap-2">
|
||||
<span className="flex items-center justify-center w-6 h-6 bg-red-600 text-white rounded-full text-xs mr-2">
|
||||
6
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={!selectedFile || isUploading}
|
||||
>
|
||||
{isUploading ? '업로드중...' : '확인'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default ListUploadDialog
|
||||
188
src/components/dialog/UserUploadDialog.tsx
Normal file
188
src/components/dialog/UserUploadDialog.tsx
Normal file
@@ -0,0 +1,188 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useState, useRef } from 'react'
|
||||
import {Download, Upload, X} from 'lucide-react'
|
||||
import { useLoading } from '@/hooks/useLoading'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import {apiError} from "@/lib/http-util";
|
||||
|
||||
export type UserUploadDialogProps = {
|
||||
/** jotai로 관리할 dialog id (기본값: 'userUploadDialog') */
|
||||
dialogId?: DialogId
|
||||
|
||||
/** 필요하면 부모에서 직접 제어도 가능 */
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
|
||||
onUpload: (file: File) => void | Promise<void>
|
||||
onDownloadTemplate?: () => void | Promise<void>
|
||||
}
|
||||
|
||||
const UserUploadDialog = ({
|
||||
dialogId = 'userUploadDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
onUpload,
|
||||
onDownloadTemplate,
|
||||
}: UserUploadDialogProps) => {
|
||||
const { withLoadingAsync } = useLoading()
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog()
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
//실제 Dialog에 넘길 open값 (props 우선, 없으면 jotai 사용)
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId)
|
||||
|
||||
// open change 공통 처리 (부모 콜백 + jotai 동시 반영)
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
// 1) 부모 콜백 먼저
|
||||
onOpenChange?.(nextOpen)
|
||||
|
||||
// 2) jotai 상태 업데이트
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId)
|
||||
} else {
|
||||
hideDialog(dialogId)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
const allowedTypes = [
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'text/csv',
|
||||
]
|
||||
|
||||
if (
|
||||
allowedTypes.includes(file.type) ||
|
||||
file.name.endsWith('.xlsx') ||
|
||||
file.name.endsWith('.xls') ||
|
||||
file.name.endsWith('.csv')
|
||||
) {
|
||||
setSelectedFile(file)
|
||||
} else {
|
||||
alert('엑셀 파일만 업로드 가능합니다. (.xlsx, .xls, .csv)')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveFile = () => {
|
||||
setSelectedFile(null)
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadClick = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedFile) {
|
||||
alert('파일을 선택해주세요.')
|
||||
return
|
||||
}
|
||||
|
||||
withLoadingAsync(async () => {
|
||||
try {
|
||||
await onUpload(selectedFile)
|
||||
// 성공 시 초기화 + 닫기
|
||||
handleRemoveFile()
|
||||
handleOpenChange(false)
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
alert('업로드에 실패했습니다.')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ✅ Dialog에서 닫힐 때: 파일도 초기화 + 상태 닫기
|
||||
const handleDialogOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen) {
|
||||
handleRemoveFile()
|
||||
}
|
||||
handleOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className=" content-text-2xl font-bold">엑셀 업로드</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 py-4">
|
||||
<div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
className="content-text-lg bg-green-600 hover:bg-green-700"
|
||||
onClick={onDownloadTemplate}
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="flex-1 content-text-lg w-full"
|
||||
onClick={handleUploadClick}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
{selectedFile ? selectedFile.name : '선택된 파일 없음'}
|
||||
</Button>
|
||||
<div className="w-9 h-8">
|
||||
{selectedFile && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleRemoveFile}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<div className="flex items-center justify-end w-full gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSubmit}
|
||||
disabled={!selectedFile}
|
||||
>
|
||||
확인
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default UserUploadDialog
|
||||
299
src/components/dialog/UserUpsertDialog.tsx
Normal file
299
src/components/dialog/UserUpsertDialog.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useDialog } from '@/hooks/useDialog'
|
||||
import type { DialogId } from '@/store/jotai/dialog'
|
||||
import { UserInfoSaveRequest } from '@/types/user'
|
||||
import KriPassword from "@/components/common/KriPassword";
|
||||
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
||||
import {DataVerification} from "@/types/common";
|
||||
import commonConst from "@/config/commonConst";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
|
||||
export type UserUpsertDialogProps = {
|
||||
/** Jotai로 관리할 다이얼로그 ID (기본값: 'userUpsertDialog') */
|
||||
dialogId?: DialogId
|
||||
|
||||
/** 필요하면 여전히 외부에서 open 제어도 가능하게 */
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
|
||||
mode?: 'create' | 'edit'
|
||||
initialData?: Partial<UserInfoSaveRequest>
|
||||
isInternal: boolean
|
||||
userCmpn: string
|
||||
userCmpnArray: string[]
|
||||
userRoleArray: KriSelectItem[]
|
||||
onSubmit: (data: UserInfoSaveRequest) => void | Promise<void>
|
||||
onCheckDuplicate?: (userId: string) => DataVerification | Promise<DataVerification>
|
||||
}
|
||||
|
||||
const UserUpsertDialog = ({
|
||||
dialogId = 'userUpsertDialog',
|
||||
open,
|
||||
onOpenChange,
|
||||
mode = 'create',
|
||||
initialData,
|
||||
isInternal,
|
||||
userCmpn,
|
||||
userCmpnArray,
|
||||
userRoleArray,
|
||||
onSubmit,
|
||||
onCheckDuplicate,
|
||||
}: UserUpsertDialogProps) => {
|
||||
const defaultUserInfo:UserInfoSaveRequest = {
|
||||
userId: '',
|
||||
userPw: '',
|
||||
userName: '',
|
||||
userCmpn: userCmpn,
|
||||
userTeam: '',
|
||||
userRole: 9002,
|
||||
memo: '',
|
||||
}
|
||||
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog();
|
||||
|
||||
const [formData, setFormData] = useState<UserInfoSaveRequest>(defaultUserInfo);
|
||||
|
||||
const [isCheckedDuplicate, setIsCheckedDuplicate] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// 🔹 실제로 Dialog에 넘길 open 값 (외부 open 있으면 우선)
|
||||
const resolvedOpen = open ?? isDialogOpen(dialogId);
|
||||
|
||||
// 🔹 실제 onOpenChange 핸들러 (외부 콜백 + jotai 둘 다 처리)
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
// 1) 외부에서 넘겨준 onOpenChange 먼저 호출
|
||||
onOpenChange?.(nextOpen);
|
||||
|
||||
// 2) jotai 전역 상태도 함께 업데이트
|
||||
if (nextOpen) {
|
||||
showDialog(dialogId);
|
||||
} else {
|
||||
hideDialog(dialogId);
|
||||
}
|
||||
}
|
||||
|
||||
// initialData / mode / open 변경 시 폼 세팅
|
||||
useEffect(() => {
|
||||
if (initialData) {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
...initialData,
|
||||
}));
|
||||
|
||||
if (mode === 'edit'){
|
||||
setIsCheckedDuplicate(true);
|
||||
}
|
||||
} else {
|
||||
setFormData(defaultUserInfo);
|
||||
setIsCheckedDuplicate(false);
|
||||
}
|
||||
}, [initialData, mode, resolvedOpen])
|
||||
|
||||
const handleInputChange = (field: keyof UserInfoSaveRequest, value: any) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
|
||||
if (field === 'userId' && mode === 'create') {
|
||||
setIsCheckedDuplicate(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleCheckDuplicate = async () => {
|
||||
if (!formData.userId.trim()) {
|
||||
alert('아이디를 입력해주세요.');
|
||||
return
|
||||
}
|
||||
|
||||
if (onCheckDuplicate) {
|
||||
const isDuplicate = await onCheckDuplicate(formData.userId);
|
||||
if (!isDuplicate.success) {
|
||||
alert(isDuplicate.errMessage);
|
||||
setIsCheckedDuplicate(false);
|
||||
} else {
|
||||
alert('사용 가능한 아이디입니다.');
|
||||
setIsCheckedDuplicate(true);
|
||||
}
|
||||
} else {
|
||||
setIsCheckedDuplicate(true);
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!formData.userId.trim()) {
|
||||
alert('아이디를 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if (mode === 'create' && !isCheckedDuplicate) {
|
||||
alert('아이디 중복체크를 해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!formData.userPw.trim()) {
|
||||
alert('비밀번호를 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!formData.userName.trim()) {
|
||||
alert('이름을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if(!commonConst.nameRegex.test(formData.userName)){
|
||||
alert('올바르지 않은 이름입니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await onSubmit(formData as UserInfoSaveRequest);
|
||||
handleOpenChange(false);
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
if(err.code !== commonConst.noneHttpError && err.code !== commonConst.unknownHttpError){
|
||||
alert(err.message);
|
||||
}
|
||||
else{
|
||||
alert('저장에 실패했습니다.');
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px] content-text-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="content-text-sxl">
|
||||
{mode === 'create' ? '계정 등록' : '계정 수정'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>면접원 계정 정보를 입력해주세요.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="userId">
|
||||
ID<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="userId"
|
||||
placeholder="아이디를 입력하세요"
|
||||
value={formData.userId}
|
||||
onChange={(e) => handleInputChange('userId', e.target.value)}
|
||||
disabled={mode === 'edit'}
|
||||
/>
|
||||
{mode === 'create' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCheckDuplicate}
|
||||
disabled={!formData.userId.trim() || isCheckedDuplicate}
|
||||
>
|
||||
{isCheckedDuplicate ? '확인완료' : '중복체크'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password">
|
||||
PW<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<KriPassword
|
||||
id="password"
|
||||
value={formData.userPw}
|
||||
onChange={(v) => handleInputChange('userPw', v)}
|
||||
placeholder="비밀번호를 입력하세요"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="userName">
|
||||
이름<span className="text-red-500 ml-1">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="userName"
|
||||
placeholder="이름을 입력하세요"
|
||||
value={formData.userName}
|
||||
onChange={(e) => handleInputChange('userName', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>계정 권한</Label>
|
||||
<KriSingleSelect
|
||||
items={userRoleArray}
|
||||
value={String(formData.userRole)}
|
||||
onChange={(e) => handleInputChange('userRole', Number(e))}
|
||||
getLabel={(item) => item.label}
|
||||
getValue={(item) => String(item.value)}
|
||||
placeholder="사용자 권한"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>소속 회사</Label>
|
||||
{
|
||||
isInternal && formData.userRole > 9000 ?
|
||||
<KriSingleSelect
|
||||
items={userCmpnArray}
|
||||
value={formData.userCmpn}
|
||||
onChange={(e) => handleInputChange('userCmpn', e)}
|
||||
placeholder="소속 회사"
|
||||
widthClassName="w-full"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
:
|
||||
<Input
|
||||
id="userCmpn"
|
||||
placeholder="소속 회사를 입력하세요"
|
||||
value={formData.userCmpn}
|
||||
disabled={!isInternal}
|
||||
onChange={(e) => handleInputChange('userCmpn', e.target.value)}
|
||||
/>
|
||||
}
|
||||
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="memo">메모</Label>
|
||||
<textarea id="memo" className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
rows={3}
|
||||
placeholder="메모를 입력하세요"
|
||||
value={formData.memo}
|
||||
onChange={(e) => handleInputChange('memo', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{mode === 'create' ? '등록' : '수정'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default UserUpsertDialog
|
||||
13
src/components/layout/BodyTitle.tsx
Normal file
13
src/components/layout/BodyTitle.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
interface BodyTitleProps {
|
||||
titleText: string;
|
||||
}
|
||||
|
||||
const BodyTitle = ({titleText}:BodyTitleProps) => {
|
||||
return (
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="font-bold content-text-4xl">{titleText}</h1>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default BodyTitle
|
||||
@@ -4,6 +4,9 @@ import { Button } from "@/components/ui/button";
|
||||
import { Menu, X, ZoomIn, ZoomOut, LogOut } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
import { topMenus } from "@/config/menu.data";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import type {LoginUser} from "@/types/auth";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
interface HeaderProps {
|
||||
isMain: boolean;
|
||||
@@ -28,6 +31,15 @@ export const Header = ({
|
||||
decreaseFontSize,
|
||||
increaseFontSize,
|
||||
}: HeaderProps) => {
|
||||
const { auth } = useAuth();
|
||||
const [userInfo, setUserInfo] = useState<LoginUser|undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
setUserInfo(auth.user);
|
||||
}
|
||||
}, [auth])
|
||||
|
||||
return (
|
||||
<header className="bg-white border-b border-gray-200 sticky top-0 z-40">
|
||||
<div className="flex items-center justify-between px-4 h-16">
|
||||
@@ -38,7 +50,6 @@ export const Header = ({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="cursor-pointer"
|
||||
onClick={() => onToggleMenu()}
|
||||
>
|
||||
{menuOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
|
||||
@@ -68,7 +79,6 @@ export const Header = ({
|
||||
<Button
|
||||
key={m.id}
|
||||
variant={activeTopId === m.id ? "default" : "ghost"}
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
handleIsProjectMenu(m.id === "project");
|
||||
onNavigate(m.path);
|
||||
@@ -103,7 +113,7 @@ export const Header = ({
|
||||
<ZoomIn className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<span className="text-sm text-gray-600 hidden sm:inline">admin</span>
|
||||
<span className="text-sm text-gray-600 hidden sm:inline">{userInfo?.userName || ""}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
|
||||
@@ -104,7 +104,7 @@ const MainLayout = ({ children, initialFontSize }: MainLayoutProps) => {
|
||||
|
||||
{/* 메인 콘텐츠만 가변 폰트 크기 적용 */}
|
||||
<main
|
||||
className="flex-1"
|
||||
className="flex-1 p-4"
|
||||
// 전역 CSS 변수(--content-font-size)를 실제 렌더에 적용
|
||||
// SSR 단계에서의 초기 폰트 값을 FOUC 없이 유지하기 위해 fallback을 함께 지정
|
||||
style={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
|
||||
|
||||
@@ -51,7 +51,7 @@ export const Sidebar = ({
|
||||
`}
|
||||
>
|
||||
<div className="p-4 space-y-4 overflow-y-auto h-full">
|
||||
{isProjectMenu?
|
||||
{isProjectMenu && (
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
type="text"
|
||||
@@ -59,8 +59,7 @@ export const Sidebar = ({
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
: null
|
||||
}
|
||||
)}
|
||||
|
||||
{/* 좌측 메뉴 */}
|
||||
<nav className="space-y-1">
|
||||
|
||||
@@ -51,7 +51,7 @@ function Button({
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
className={cn(buttonVariants({ variant, size, className }), "cursor-pointer")}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -11,6 +11,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
"placeholder-content-text-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
1315
src/components/ui/multi-select.tsx
Normal file
1315
src/components/ui/multi-select.tsx
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user