251201_01_ENH : datatable, autocomplete, user관리 완성

This commit is contained in:
2025-12-02 13:45:35 +09:00
parent 74de3d58f7
commit 310506d9ef
45 changed files with 5313 additions and 368 deletions

View 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

View 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

View 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