251201_01_ENH : datatable, autocomplete, user관리 완성
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
NEXT_PUBLIC_ENV=dev
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
|
||||
ENV=dev
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
@@ -1,5 +1,5 @@
|
||||
NEXT_PUBLIC_ENV=local
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
|
||||
ENV=local
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
@@ -1,5 +1,5 @@
|
||||
NEXT_PUBLIC_ENV=prod
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:3000/api
|
||||
|
||||
ENV=prod
|
||||
API_CONTACT_SERVER=http://localhost:4001/api/v1
|
||||
1030
package-lock.json
generated
1030
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
@@ -9,11 +9,22 @@
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
"@radix-ui/react-radio-group": "^1.3.8",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@types/lodash": "^4.17.21",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"jotai": "^2.15.1",
|
||||
"lodash": "^4.17.21",
|
||||
"lucide-react": "^0.553.0",
|
||||
"next": "16.0.2",
|
||||
"next-themes": "^0.4.6",
|
||||
|
||||
73
src/app/(pages)/(main)/manage/user/UserTableColumn.tsx
Normal file
73
src/app/(pages)/(main)/manage/user/UserTableColumn.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import {ColumnDef} from "@tanstack/react-table";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Pencil, Trash2} from "lucide-react";
|
||||
import {UserTableInfo} from "@/types/user";
|
||||
|
||||
|
||||
|
||||
export type UserColumnsActions = {
|
||||
onEdit: (userId: string) => void
|
||||
onDelete: (userId: string) => void
|
||||
}
|
||||
|
||||
export const getUserColumns = (actions: UserColumnsActions): ColumnDef<UserTableInfo>[] => [
|
||||
{
|
||||
accessorKey: "userId",
|
||||
header: "아이디",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "userCmpn",
|
||||
header: "소속",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "userName",
|
||||
header: "이름",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "userRole",
|
||||
header: "권한",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "regDt",
|
||||
header: "등록일",
|
||||
enableSorting: true,
|
||||
},
|
||||
{
|
||||
accessorKey: "memo",
|
||||
header: "메모",
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "관리",
|
||||
cell: ({ row }) => (
|
||||
<div
|
||||
className="flex items-center justify-center gap-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => actions.onEdit(row.original.userId)}
|
||||
aria-label="수정"
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => actions.onDelete(row.original.userId)}
|
||||
aria-label="삭제"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false,
|
||||
},
|
||||
];
|
||||
@@ -1,8 +1,280 @@
|
||||
const UserManagePage = () => {
|
||||
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
|
||||
//redirect(url);
|
||||
'use client'
|
||||
import {useEffect, useState} from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import { DataTable } from "@/components/data-table/DataTable";
|
||||
import { getUserColumns } from "./UserTableColumn";
|
||||
import _ from "lodash";
|
||||
import UserUpsertDialog from "@/components/dialog/UserUpsertDialog";
|
||||
import {UserInfo, UserInfoSaveRequest, UserTableInfo, UserUploadResponse} from "@/types/user";
|
||||
import UserUploadDialog from "@/components/dialog/UserUploadDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {downloadBase64File, downloadFile, formatKst} from "@/lib/utils";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {DataVerification} from "@/types/common";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
|
||||
import commonConst from "@/config/commonConst";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
|
||||
return (<div>This is User Manage Page</div>)
|
||||
const UserManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { auth } = useAuth();
|
||||
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [userList, setUserList] = useState<UserTableInfo[]>([]);
|
||||
const [viewList, setViewList] = useState<UserTableInfo[]>([]);
|
||||
const [selectedUserArray, setSelectedUserArray] = useState<UserTableInfo[]>([]);
|
||||
const [userCmpnArray, setUserCmpnArray] = useState<string[]>([]);
|
||||
const [userRoleArray, setUserRoleArray] = useState<MultiSelectOption[]>([]);
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchCmpn, setSearchCmpn] = useState<string[]>([]);
|
||||
const [searchRole, setSearchRole] = useState<string[]>([]);
|
||||
|
||||
const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create')
|
||||
const [editData, setEditData] = useState<Partial<UserInfoSaveRequest>>();
|
||||
|
||||
const setUserData = async () => {
|
||||
const roleList = await nextApi.get<RoleInfo[]>("/role");
|
||||
setUserRoleArray(
|
||||
roleList.map((role) => ({
|
||||
value: String(role.roleCd),
|
||||
label: role.roleNm,
|
||||
}))
|
||||
);
|
||||
|
||||
const cmpnList = await nextApi.get<string[]>("/user/cmpn");
|
||||
setUserCmpnArray(cmpnList);
|
||||
|
||||
const userData: UserTableInfo[] = (await nextApi.get<UserInfo[]>("/user")).map((user) => {
|
||||
const role = roleList.filter((r) => r.roleCd === user.userRole);
|
||||
const roleName = role.length > 0 ? role[0].roleNm : String(user.userRole);
|
||||
return {
|
||||
userId: user.userId,
|
||||
userCmpn: user.userCmpn,
|
||||
userName: user.userName,
|
||||
userRole: roleName,
|
||||
regDt: formatKst(user.regDt ?? "", "date"),
|
||||
memo: user.memo ?? "",
|
||||
}
|
||||
});
|
||||
|
||||
setUserList(userData);
|
||||
|
||||
const cmpnArray = Array.from(
|
||||
new Set(userData.map(u => u.userCmpn).filter(Boolean))
|
||||
).sort((a, b) => a.localeCompare(b, "ko"));
|
||||
setUserCmpnArray(cmpnArray);
|
||||
}
|
||||
|
||||
// 등록 버튼 클릭
|
||||
const handleCreateClick = () => {
|
||||
setDialogMode('create');
|
||||
setEditData(undefined);
|
||||
showDialog('userUpsertDialog');
|
||||
}
|
||||
|
||||
// 중복 체크
|
||||
const handleCheckDuplicate = async (userId: string): Promise<DataVerification> => {
|
||||
return nextApi.get<DataVerification>("/user/check-user-id", {
|
||||
query: { userId },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
const handleSubmit = async (data: UserInfoSaveRequest): Promise<void> => {
|
||||
if (dialogMode === 'create') {
|
||||
await nextApi.put<void>("/user", data);
|
||||
} else {
|
||||
await nextApi.patch<void>("/user", data);
|
||||
}
|
||||
await setUserData();
|
||||
}
|
||||
|
||||
const handleEdit = (userId: string) => {
|
||||
setDialogMode('edit');
|
||||
nextApi.get<UserInfo>(`/user/${userId}`)
|
||||
.then((data) => {
|
||||
setEditData(data);
|
||||
showDialog('userUpsertDialog');
|
||||
})
|
||||
.catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
});
|
||||
// 수정 로직 또는 모달 열기
|
||||
}
|
||||
|
||||
const handleDelete = (userId: string) => {
|
||||
// 삭제 확인 후 데이터 삭제
|
||||
if (confirm('정말 삭제하시겠습니까?')) {
|
||||
//삭제
|
||||
nextApi.del<void>(`/user/${encodeURIComponent(userId)}`)
|
||||
.then(async () => {
|
||||
alert("삭제 됐습니다.");
|
||||
await setUserData();
|
||||
})
|
||||
.catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file); // key 이름은 백엔드 @RequestPart("file") 와 동일해야 함
|
||||
|
||||
const res = await nextApi.postForm<UserUploadResponse>("/user/excel", formData);
|
||||
|
||||
if (res.hasErrorFile && res.errorFileBase64) {
|
||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx");
|
||||
}
|
||||
else{
|
||||
await setUserData();
|
||||
}
|
||||
}
|
||||
|
||||
const downloadTemplate = async () => {
|
||||
const buffer = await nextApi.post<ArrayBuffer>(
|
||||
"/user/excel-template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
if (buffer.byteLength > 0) {
|
||||
const blob = new Blob([buffer], {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
downloadFile(blob, "사용자 업로드 양식.xlsx");
|
||||
alert("다운로드 됐습니다.");
|
||||
} else {
|
||||
console.log("빈 파일입니다.");
|
||||
}
|
||||
}
|
||||
|
||||
const columns = getUserColumns({
|
||||
onEdit: handleEdit,
|
||||
onDelete: handleDelete
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(setUserData);
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let tempData = _.cloneDeep(userList);
|
||||
const keyword = searchText.trim();
|
||||
if (keyword){
|
||||
tempData = tempData.filter((row) =>
|
||||
[row.userId, row.userName].some((v) => v.toLowerCase().includes(keyword.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
if(searchCmpn.length > 0){
|
||||
tempData = tempData.filter((row) => searchCmpn.includes(row.userCmpn));
|
||||
}
|
||||
|
||||
if(searchRole.length > 0){
|
||||
tempData = tempData.filter((row) => searchRole.includes(row.userRole));
|
||||
}
|
||||
|
||||
setViewList(tempData);
|
||||
}, [searchText, searchCmpn, searchRole, userList]);
|
||||
|
||||
const isInternal =
|
||||
mounted &&
|
||||
auth.user?.userRole != null &&
|
||||
auth.user.userRole < commonConst.externalUserRole
|
||||
|
||||
const userCmpn = auth.user?.userCmpn ?? commonConst.defaultCmpn;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 content-text-sm">
|
||||
<BodyTitle titleText={"계정 관리"}/>
|
||||
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<Input
|
||||
placeholder="면접원 ID Or 면접원 이름"
|
||||
className="w-70 h-9 bg-white"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
/>
|
||||
{
|
||||
isInternal &&
|
||||
<KriMultiSelect
|
||||
items={userCmpnArray}
|
||||
value={searchCmpn}
|
||||
onChange={setSearchCmpn}
|
||||
placeholder="소속 회사"
|
||||
widthClassName="w-70"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
}
|
||||
<KriMultiSelect
|
||||
items={userRoleArray}
|
||||
value={searchRole}
|
||||
onChange={setSearchRole}
|
||||
getValue={(item) => item.label}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="사용자 권한"
|
||||
widthClassName="w-70"
|
||||
heightClassName="h-9"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="content-text-lg"
|
||||
onClick={handleCreateClick}
|
||||
>
|
||||
면접원 등록
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => showDialog('userUploadDialog')}
|
||||
className="gap-2 bg-green-600 hover:bg-green-700 content-text-lg"
|
||||
>
|
||||
면접원 일괄 등록
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={viewList}
|
||||
isClient={true}
|
||||
selectMode='single'
|
||||
enableRowClickSelection={true}
|
||||
onRowSelectionChange={setSelectedUserArray}
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.userId} // row.id = userId
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UserUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={editData}
|
||||
isInternal={isInternal}
|
||||
userCmpn={userCmpn}
|
||||
userCmpnArray={userCmpnArray}
|
||||
userRoleArray={userRoleArray}
|
||||
onSubmit={handleSubmit}
|
||||
onCheckDuplicate={handleCheckDuplicate}
|
||||
/>
|
||||
|
||||
<UserUploadDialog
|
||||
onUpload={uploadFile}
|
||||
onDownloadTemplate={downloadTemplate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default UserManagePage;
|
||||
@@ -12,6 +12,8 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { useLoading } from "@/hooks/useLoading";
|
||||
import { useStorage } from "@/hooks/useStorage"
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import commonConst from "@/config/commonConst";
|
||||
|
||||
const LoginPage = () => {
|
||||
const router = useRouter();
|
||||
@@ -49,7 +51,7 @@ const LoginPage = () => {
|
||||
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
|
||||
return withLoadingAsync(() =>
|
||||
nextApi.post<LoginUser>(
|
||||
"/api/login", loginRequestBody, loginRequestOptions
|
||||
"/login", loginRequestBody, loginRequestOptions
|
||||
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신
|
||||
setFromLoginResponse(data, seatNum);
|
||||
// 요구사항: 페이지 이동 전에 SeatNumber를 secure-local-storage에 저장
|
||||
@@ -62,17 +64,19 @@ const LoginPage = () => {
|
||||
}
|
||||
// 메인 페이지로 이동 (보호 라우트 진입)
|
||||
router.replace("/");
|
||||
}).catch((err) => {
|
||||
if (err instanceof HttpError) {
|
||||
if (err.status === 401 || err.status === 403) {
|
||||
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
} else {
|
||||
setError(`로그인에 실패했습니다. (status: ${err.status})`);
|
||||
}
|
||||
} else {
|
||||
console.error(err);
|
||||
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
}
|
||||
}).catch((e) => {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
|
||||
if (err.status === 401 || err.status === 403) {
|
||||
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
}
|
||||
else if(err.code === commonConst.noneHttpError) {
|
||||
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
}
|
||||
else {
|
||||
setError(`로그인에 실패했습니다. (status: ${err.status})`);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,23 +7,27 @@ import {StorageKeys} from "@/store/storage/storage-keys";
|
||||
import {useEffect} from "react";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
|
||||
const LogoutPage = () => {
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
const { logout } = useAuth();
|
||||
const { auth, logout } = useAuth();
|
||||
const { clearSelectedProject } = useSelectedProject();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
const runLogout = async () => {
|
||||
const userId = auth.user?.userId ?? "";
|
||||
clearSelectedProject();
|
||||
logout();
|
||||
|
||||
try {
|
||||
await nextApi.del("/api/logout", {});
|
||||
await nextApi.post(`/logout/${userId}`);
|
||||
} catch (e) {
|
||||
console.error("로그아웃 API 호출 실패", e);
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
}
|
||||
|
||||
const loginType = getLoginTypeStorage();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import {LoginRequest, LoginUser} from "@/types/auth";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
|
||||
//실제 Backend
|
||||
type LoginResponse = {
|
||||
@@ -27,61 +28,6 @@ export const POST = async (req: NextRequest) => {
|
||||
|
||||
return res;
|
||||
} catch (error : unknown) {
|
||||
const err = error as { status?: number; data?: unknown };
|
||||
const status = typeof err.status === "number" ? err.status : 500;
|
||||
const payload = err.data !== undefined ? err.data : { message: "서버에서 오류 응답을 받았습니다." };
|
||||
|
||||
return NextResponse.json(payload, { status });
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
if (error instanceof HttpError) {
|
||||
const status = error.status;
|
||||
|
||||
// 서버에서 내려준 message 추출 (있으면)
|
||||
let serverMessage: string | undefined;
|
||||
if (typeof error.data === "object" && error.data !== null && "message" in error.data) {
|
||||
serverMessage = String((error.data as { message?: unknown }).message ?? "");
|
||||
} else if (typeof error.data === "string") {
|
||||
serverMessage = error.data;
|
||||
}
|
||||
|
||||
// status별로 클라이언트에 내려줄 메시지 매핑
|
||||
let clientMessage: string;
|
||||
|
||||
switch (status) {
|
||||
case 400:
|
||||
clientMessage = serverMessage || "요청 형식이 올바르지 않습니다.";
|
||||
break;
|
||||
case 401:
|
||||
clientMessage = serverMessage || "아이디 또는 비밀번호를 다시 확인해주세요.";
|
||||
break;
|
||||
case 403:
|
||||
clientMessage = serverMessage || "해당 계정으로는 접근할 수 없습니다.";
|
||||
break;
|
||||
case 404:
|
||||
clientMessage = serverMessage || "로그인 정보를 확인할 수 없습니다.";
|
||||
break;
|
||||
case 429:
|
||||
clientMessage = serverMessage || "로그인 시도가 너무 많습니다. 잠시 후 다시 시도해주세요.";
|
||||
break;
|
||||
default:
|
||||
// 5xx 등 기타
|
||||
clientMessage = serverMessage || "로그인 처리 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.";
|
||||
break;
|
||||
}
|
||||
|
||||
// traceId가 있으면 같이 내려줘서 디버깅에 활용
|
||||
return NextResponse.json(
|
||||
{
|
||||
message: clientMessage,
|
||||
traceId: error.traceId,
|
||||
},
|
||||
{
|
||||
status,
|
||||
}
|
||||
);
|
||||
}
|
||||
*/
|
||||
}
|
||||
37
src/app/api/logout/[[...slug]]/route.ts
Normal file
37
src/app/api/logout/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {RouteContext} from "@/types/common";
|
||||
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
const [userId] = slug;
|
||||
|
||||
const url = userId
|
||||
? `/auth/logout/${encodeURIComponent(userId)}`
|
||||
: "/auth/logout/";
|
||||
|
||||
await contactApi.post<boolean>(url);
|
||||
|
||||
const res = NextResponse.json({ ok: true });
|
||||
|
||||
res.cookies.set("access_token", "", {
|
||||
httpOnly: true,
|
||||
secure: serverEnv.ENV === "prod",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
});
|
||||
|
||||
return res;
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
|
||||
export async function DELETE() {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
|
||||
res.cookies.set("access_token", "", {
|
||||
httpOnly: true,
|
||||
secure: serverEnv.ENV === "prod",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
});
|
||||
|
||||
return res;
|
||||
}
|
||||
64
src/app/api/project/[[...slug]]/route.ts
Normal file
64
src/app/api/project/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import {NextRequest} from "next/server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {RouteContext} from "@/types/common";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
import {NextRequest} from "next/server";
|
||||
|
||||
export const GET = async (req: NextRequest) => {
|
||||
|
||||
}
|
||||
22
src/app/api/role/[[...slug]]/route.ts
Normal file
22
src/app/api/role/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createContactApi} from "@/lib/server-api";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {RouteContext} from "@/types/common";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const result = await contactApi.get<RoleInfo[]>("/role");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
166
src/app/api/user/[[...slug]]/route.ts
Normal file
166
src/app/api/user/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createContactApi } from "@/lib/server-api";
|
||||
import {UserInfo, UserUploadResponse} from "@/types/user";
|
||||
import {DataVerification, RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
|
||||
export const GET = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug;
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "check-user-id") {
|
||||
const userId = req.nextUrl.searchParams.get("userId") ?? "";
|
||||
if (!userId) {
|
||||
return NextResponse.json(
|
||||
{ message: "userId 파라미터가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await contactApi.get<DataVerification>("/user/check-user-id", {
|
||||
query: { userId },
|
||||
});
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "cmpn"){
|
||||
const result = await contactApi.get<string[]>("/user/cmpn");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
const result = await contactApi.get<UserInfo[]>("/user");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (slug.length === 1) {
|
||||
const userId = action;
|
||||
const result = await contactApi.get<UserInfo>(`/user/${encodeURIComponent(userId)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (action === "excel") {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json(
|
||||
{ message: "file 필드가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const backendForm = new FormData();
|
||||
backendForm.append("file", file, file.name);
|
||||
|
||||
const result = await contactApi.postForm<UserUploadResponse>(
|
||||
"/user/excel",
|
||||
backendForm
|
||||
);
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "excel-template") {
|
||||
const result = await contactApi.post<ArrayBuffer>(
|
||||
"/user/excel/template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result as any, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type":
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"Content-Disposition":
|
||||
'attachment; filename="user_upload_template.xlsx"',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if(!action){
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.put("/user", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export const PATCH = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [action] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await contactApi.patch("/user", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (req: NextRequest, context: RouteContext) => {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
const [userId] = slug ?? [];
|
||||
const contactApi = await createContactApi();
|
||||
|
||||
if (userId) {
|
||||
await contactApi.del<void>(`/user/${encodeURIComponent(userId)}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -76,6 +76,7 @@
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
--content-font-size: 14px;
|
||||
}
|
||||
|
||||
.dark {
|
||||
@@ -112,6 +113,73 @@
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
/* 배율별 유틸 클래스 */
|
||||
.content-text-xs {
|
||||
font-size: calc(var(--content-font-size) * 0.75);
|
||||
}
|
||||
|
||||
.content-text-sm {
|
||||
font-size: calc(var(--content-font-size) * 0.875);
|
||||
}
|
||||
|
||||
.content-text-base {
|
||||
font-size: var(--content-font-size);
|
||||
}
|
||||
|
||||
.content-text-lg {
|
||||
font-size: calc(var(--content-font-size) * 1.125);
|
||||
}
|
||||
|
||||
.content-text-xl {
|
||||
font-size: calc(var(--content-font-size) * 1.25);
|
||||
}
|
||||
|
||||
.content-text-2xl {
|
||||
font-size: calc(var(--content-font-size) * 1.5);
|
||||
}
|
||||
|
||||
.content-text-3xl {
|
||||
font-size: calc(var(--content-font-size) * 1.875);
|
||||
}
|
||||
|
||||
.content-text-4xl {
|
||||
font-size: calc(var(--content-font-size) * 2.25);
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.placeholder-content-text-xs::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 0.75);
|
||||
}
|
||||
|
||||
.placeholder-content-text-sm::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 0.875);
|
||||
}
|
||||
|
||||
.placeholder-content-text-base::placeholder {
|
||||
font-size: var(--content-font-size);
|
||||
}
|
||||
|
||||
.placeholder-content-text-lg::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.125);
|
||||
}
|
||||
|
||||
.placeholder-content-text-xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.25);
|
||||
}
|
||||
|
||||
.placeholder-content-text-2xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.5);
|
||||
}
|
||||
|
||||
.placeholder-content-text-3xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 1.875);
|
||||
}
|
||||
|
||||
.placeholder-content-text-4xl::placeholder {
|
||||
font-size: calc(var(--content-font-size) * 2.25);
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
|
||||
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
@@ -2,6 +2,11 @@ const commonConst = {
|
||||
fontSizeDefault: 14,
|
||||
fontSizeMin: 12,
|
||||
fontSizeMax: 24,
|
||||
externalUserRole: 4000,
|
||||
unknownHttpError: 'UNKNOWN_HTTP_ERROR',
|
||||
noneHttpError: 'NONE_HTTP_ERROR',
|
||||
nameRegex: /^[가-힣A-Za-z][가-힣A-Za-z0-9_ ()]*$/,
|
||||
defaultCmpn: 'KRI',
|
||||
} as const;
|
||||
|
||||
export default commonConst;
|
||||
54
src/hooks/useDialog.ts
Normal file
54
src/hooks/useDialog.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { useAtom } from 'jotai'
|
||||
import {DialogId, openDialogIdsAtom} from "@/store/jotai/dialog";
|
||||
|
||||
export function useDialog() {
|
||||
const [openDialogIds, setOpenDialogIds] = useAtom(openDialogIdsAtom)
|
||||
|
||||
/**
|
||||
* 다이얼로그 열기
|
||||
* @param dialogId 다이얼로그를 구분할 ID
|
||||
* @param onlyThis true 이면 기존 다이얼로그 전부 닫고 이 것만 연다.
|
||||
* false 이면 기존 배열에 추가한다.
|
||||
*/
|
||||
const showDialog = (dialogId: DialogId, onlyThis: boolean = true) => {
|
||||
setOpenDialogIds(prev => {
|
||||
if (onlyThis) {
|
||||
// 이 다이얼로그만 열기
|
||||
return [dialogId]
|
||||
}
|
||||
|
||||
// 이미 열려 있으면 그대로
|
||||
if (prev.includes(dialogId)) {
|
||||
return prev
|
||||
}
|
||||
|
||||
// 여러 개 동시에 열기 허용
|
||||
return [...prev, dialogId]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 다이얼로그 닫기
|
||||
*/
|
||||
const hideDialog = (dialogId: DialogId) => {
|
||||
setOpenDialogIds(prev => prev.filter(id => id !== dialogId))
|
||||
}
|
||||
|
||||
/**
|
||||
* 다이얼로그 열려있는지 여부
|
||||
*/
|
||||
const isDialogOpen = (dialogId: DialogId) => openDialogIds.includes(dialogId)
|
||||
|
||||
/**
|
||||
* 모든 다이얼로그 닫기 (있으면 편하니까 같이 제공)
|
||||
*/
|
||||
const hideAll = () => setOpenDialogIds([])
|
||||
|
||||
return {
|
||||
openDialogIds,
|
||||
isDialogOpen,
|
||||
showDialog,
|
||||
hideDialog,
|
||||
hideAll,
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,32 @@
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
|
||||
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
|
||||
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
||||
|
||||
export class HttpError extends Error {
|
||||
public readonly status: number;
|
||||
public readonly data: unknown;
|
||||
public readonly url: string;
|
||||
private readonly headerMap: Record<string, string>;
|
||||
public readonly status: number;
|
||||
public readonly data: unknown;
|
||||
public readonly url: string;
|
||||
private readonly headerMap: Record<string, string>;
|
||||
|
||||
constructor(status: number, data: unknown, url: string, headers?: Headers) {
|
||||
super(`HTTP ${status}`);
|
||||
this.name = "HttpError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
this.url = url;
|
||||
this.headerMap =
|
||||
headers && typeof headers.entries === "function"
|
||||
? Object.fromEntries(headers.entries())
|
||||
: {};
|
||||
}
|
||||
constructor(status: number, data: unknown, url: string, headers?: Headers) {
|
||||
super(`HTTP ${status}`);
|
||||
this.name = "HttpError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
this.url = url;
|
||||
this.headerMap =
|
||||
headers && typeof headers.entries === "function"
|
||||
? Object.fromEntries(headers.entries())
|
||||
: {};
|
||||
}
|
||||
|
||||
/** Plain object headers (safe for logging/serialization) */
|
||||
get headers(): Record<string, string> {
|
||||
return this.headerMap;
|
||||
}
|
||||
get headers(): Record<string, string> {
|
||||
return this.headerMap;
|
||||
}
|
||||
|
||||
/** Convenience accessor for common trace headers */
|
||||
get traceId(): string | undefined {
|
||||
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
|
||||
}
|
||||
get traceId(): string | undefined {
|
||||
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
|
||||
}
|
||||
}
|
||||
|
||||
export type QueryValue = string | string[] | undefined;
|
||||
@@ -36,269 +34,263 @@ export type Query = Record<string, QueryValue>;
|
||||
export type PathParams = Record<string, string | number | boolean>;
|
||||
|
||||
export type RequestOptions = {
|
||||
/** HTTP method (default: GET or POST when body exists) */
|
||||
method?: HttpMethod;
|
||||
/** Replace placeholders in path, e.g., /users/:id */
|
||||
pathParams?: PathParams;
|
||||
/** Query string key-values (arrays supported) */
|
||||
query?: Query;
|
||||
/** JSON body (auto-serialized) */
|
||||
json?: unknown;
|
||||
/** Send raw text body */
|
||||
rawBody?: string;
|
||||
/** Send multipart/form-data */
|
||||
form?: FormData;
|
||||
/** Extra headers (merged over defaults) */
|
||||
headers?: Record<string, string>;
|
||||
/** Per-request timeout (ms), default from client */
|
||||
timeoutMs?: number;
|
||||
/** Suppress user alert on error */
|
||||
suppressAlert?: boolean;
|
||||
/** Hook for 401 responses */
|
||||
onAuthError?: () => void;
|
||||
/**
|
||||
* 401/403(토큰 만료 포함) 수신 시 자동으로 /logout 으로 이동할지 여부
|
||||
* - 기본값: true
|
||||
* - 요청 단위로 false 설정하면 자동 로그아웃을 건너뜁니다.
|
||||
*/
|
||||
autoLogoutOnAuthError?: boolean;
|
||||
/** Force treat response as text (skip JSON parse) */
|
||||
expectText?: boolean;
|
||||
method?: HttpMethod;
|
||||
pathParams?: PathParams;
|
||||
query?: Query;
|
||||
json?: unknown;
|
||||
rawBody?: string;
|
||||
form?: FormData;
|
||||
headers?: Record<string, string>;
|
||||
timeoutMs?: number;
|
||||
suppressAlert?: boolean;
|
||||
onAuthError?: () => void;
|
||||
autoLogoutOnAuthError?: boolean;
|
||||
expectText?: boolean;
|
||||
expectBinary?: boolean;
|
||||
};
|
||||
|
||||
export type HttpClientOptions = {
|
||||
/** Provide latest token per request (e.g., from storage) */
|
||||
getToken?: () => string | null;
|
||||
/** Default timeout (ms) */
|
||||
defaultTimeoutMs?: number;
|
||||
/** Default headers (e.g., content-type) */
|
||||
defaultHeaders?: Record<string, string>;
|
||||
/** Map server status/message to user-friendly text */
|
||||
setErrorMessage?: (status: number, serverMsg?: string) => string;
|
||||
getToken?: () => string | null;
|
||||
defaultTimeoutMs?: number;
|
||||
defaultHeaders?: Record<string, string>;
|
||||
setErrorMessage?: (status: number, serverMsg?: string) => string;
|
||||
};
|
||||
|
||||
const replacePathParams = (path: string, params?: PathParams): string => {
|
||||
if (!params) return path;
|
||||
let out = path;
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
const ph = `:${k}`;
|
||||
if (out.includes(ph)) out = out.replace(ph, encodeURIComponent(String(v)));
|
||||
}
|
||||
return out;
|
||||
if (!params) return path;
|
||||
let out = path;
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
const ph = `:${k}`;
|
||||
if (out.includes(ph)) out = out.replace(ph, encodeURIComponent(String(v)));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const appendQuery = (u: URL, query?: Query): void => {
|
||||
if (!query) return;
|
||||
for (const [k, v] of Object.entries(query)) {
|
||||
if (Array.isArray(v)) v.forEach((it) => u.searchParams.append(k, it));
|
||||
else if (v !== undefined) u.searchParams.set(k, v);
|
||||
}
|
||||
if (!query) return;
|
||||
for (const [k, v] of Object.entries(query)) {
|
||||
if (Array.isArray(v)) v.forEach((it) => u.searchParams.append(k, it));
|
||||
else if (v !== undefined) u.searchParams.set(k, v);
|
||||
}
|
||||
};
|
||||
|
||||
const buildHeaders = (
|
||||
base: Record<string, string>,
|
||||
extra?: Record<string, string>
|
||||
): Headers => {
|
||||
const h = new Headers(base);
|
||||
if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v);
|
||||
return h;
|
||||
const buildHeaders = (base: Record<string, string>, extra?: Record<string, string>): Headers => {
|
||||
const h = new Headers(base);
|
||||
if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v);
|
||||
return h;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a minimal, fetch-based HTTP client with:
|
||||
* - path params (:id), query, JSON/FormData/raw body
|
||||
* - default/extra headers + token injection
|
||||
* - timeout, 401 hook, optional alert suppression
|
||||
*/
|
||||
const isAbortError = (err: unknown): boolean => {
|
||||
if (!err || typeof err !== "object") return false;
|
||||
const e = err as { name?: unknown; code?: unknown; message?: unknown };
|
||||
return (
|
||||
e.name === "AbortError" || // browser fetch abort
|
||||
e.code === "ABORT_ERR" || // some runtimes
|
||||
(typeof e.message === "string" && e.message.toLowerCase().includes("aborted"))
|
||||
);
|
||||
};
|
||||
|
||||
const isJsonContentType = (ctype: string) => {
|
||||
const ct = (ctype ?? "").toLowerCase()
|
||||
return ct.includes("application/json") || ct.includes("+json")
|
||||
}
|
||||
|
||||
export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => {
|
||||
const {
|
||||
getToken,
|
||||
defaultTimeoutMs = 10_000,
|
||||
defaultHeaders = { "content-type": "application/json" },
|
||||
setErrorMessage,
|
||||
} = opts;
|
||||
const {
|
||||
getToken,
|
||||
defaultTimeoutMs = 60_000,
|
||||
defaultHeaders = { "content-type": "application/json" },
|
||||
setErrorMessage,
|
||||
} = opts;
|
||||
|
||||
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
|
||||
// 1) URL
|
||||
const replaced = replacePathParams(path, options.pathParams);
|
||||
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
|
||||
const replaced = replacePathParams(path, options.pathParams);
|
||||
|
||||
// NOTE:
|
||||
// new URL('/x', 'http://host/base') => 'http://host/x' (pathname from base is dropped)
|
||||
// We want to preserve base pathname (e.g., '/api/v1') when caller passes an absolute path like '/auth/login'.
|
||||
let url: URL;
|
||||
if (/^https?:\/\//i.test(replaced)) {
|
||||
// Fully-qualified URL: use as-is
|
||||
url = new URL(replaced);
|
||||
} else if (replaced.startsWith('/')) {
|
||||
// Absolute-like path: merge with base's pathname
|
||||
const base = new URL(baseURL);
|
||||
const joinedPath = `${base.pathname.replace(/\/+$/, '')}/${replaced.replace(/^\/+/, '')}`;
|
||||
url = new URL(base.toString());
|
||||
url.pathname = joinedPath;
|
||||
} else {
|
||||
// Relative path: URL API will correctly join with base pathname
|
||||
url = new URL(replaced, new URL(baseURL));
|
||||
let url: URL;
|
||||
if (/^https?:\/\//i.test(replaced)) {
|
||||
url = new URL(replaced);
|
||||
} else if (replaced.startsWith("/")) {
|
||||
const base = new URL(baseURL);
|
||||
const joinedPath = `${base.pathname.replace(/\/+$/, "")}/${replaced.replace(/^\/+/, "")}`;
|
||||
url = new URL(base.toString());
|
||||
url.pathname = joinedPath;
|
||||
} else {
|
||||
url = new URL(replaced, new URL(baseURL));
|
||||
}
|
||||
|
||||
appendQuery(url, options.query);
|
||||
|
||||
const base: Record<string, string> = { ...defaultHeaders };
|
||||
const token = getToken?.();
|
||||
if (token) base["authorization"] = `Bearer ${token}`;
|
||||
const headers = buildHeaders(base, options.headers);
|
||||
|
||||
let body: BodyInit | undefined;
|
||||
if (options.form) {
|
||||
headers.delete("content-type");
|
||||
body = options.form;
|
||||
} else if (options.rawBody !== undefined) {
|
||||
if (!headers.has("content-type")) headers.set("content-type", "text/plain;charset=utf-8");
|
||||
body = options.rawBody;
|
||||
} else if (options.json !== undefined) {
|
||||
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
||||
body = typeof options.json === "string" ? options.json : JSON.stringify(options.json);
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString(), {
|
||||
method: options.method ?? (body ? "POST" : "GET"),
|
||||
headers,
|
||||
body,
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (options.expectBinary) {
|
||||
if (!res.ok) {
|
||||
const rawText = await res.text().catch(() => "");
|
||||
const ctype = res.headers.get("content-type") ?? ""
|
||||
const isJson = isJsonContentType(ctype)
|
||||
|
||||
let parsedError: unknown;
|
||||
if (isJson && rawText) {
|
||||
try {
|
||||
parsedError = JSON.parse(rawText);
|
||||
} catch {
|
||||
parsedError = rawText;
|
||||
}
|
||||
} else {
|
||||
parsedError = rawText || null;
|
||||
}
|
||||
|
||||
const autoLogout = options.autoLogoutOnAuthError ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? true;
|
||||
|
||||
if (res.status === 401) options.onAuthError?.();
|
||||
|
||||
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
|
||||
try {
|
||||
window.location.replace("/logout");
|
||||
} catch {}
|
||||
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
if (!suppressAlert && typeof window !== "undefined") {
|
||||
const serverMsg =
|
||||
typeof parsedError === "object" && parsedError !== null && "message" in parsedError
|
||||
? String((parsedError as { message?: unknown }).message ?? "")
|
||||
: typeof parsedError === "string"
|
||||
? parsedError
|
||||
: undefined;
|
||||
|
||||
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
|
||||
alert(`[${res.status}] ${msg}`);
|
||||
}
|
||||
|
||||
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
appendQuery(url, options.query);
|
||||
const buffer = await res.arrayBuffer();
|
||||
return buffer as T;
|
||||
}
|
||||
|
||||
// 2) headers (defaults + token + per-call)
|
||||
const base: Record<string, string> = { ...defaultHeaders };
|
||||
const token = getToken?.();
|
||||
if (token) base["authorization"] = `Bearer ${token}`;
|
||||
const headers = buildHeaders(base, options.headers);
|
||||
const ctype = res.headers.get("content-type") ?? "";
|
||||
const isJson = isJsonContentType(ctype)
|
||||
const rawText = await res.text().catch(() => "");
|
||||
|
||||
// 3) body
|
||||
let body: BodyInit | undefined;
|
||||
if (options.form) {
|
||||
headers.delete("content-type"); // let browser set multipart boundary
|
||||
body = options.form;
|
||||
} else if (options.rawBody !== undefined) {
|
||||
if (!headers.has("content-type")) headers.set("content-type", "text/plain;charset=utf-8");
|
||||
body = options.rawBody;
|
||||
} else if (options.json !== undefined) {
|
||||
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
||||
body = typeof options.json === "string" ? options.json : JSON.stringify(options.json);
|
||||
const parsed: unknown = options.expectText
|
||||
? rawText
|
||||
: isJson
|
||||
? rawText
|
||||
? JSON.parse(rawText)
|
||||
: null
|
||||
: rawText;
|
||||
|
||||
if (!res.ok) {
|
||||
const autoLogout = options.autoLogoutOnAuthError ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? true;
|
||||
|
||||
if (res.status === 401) options.onAuthError?.();
|
||||
|
||||
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
|
||||
try {
|
||||
window.location.replace("/logout");
|
||||
} catch {}
|
||||
throw new HttpError(res.status, parsed, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
// 4) timeout
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
|
||||
if (!suppressAlert && typeof window !== "undefined") {
|
||||
const serverMsg =
|
||||
typeof parsed === "object" && parsed !== null && "message" in parsed
|
||||
? String((parsed as { message?: unknown }).message ?? "")
|
||||
: typeof parsed === "string"
|
||||
? parsed
|
||||
: undefined;
|
||||
|
||||
try {
|
||||
// 5) fetch
|
||||
const res = await fetch(url.toString(), {
|
||||
method: options.method ?? (body ? "POST" : "GET"),
|
||||
headers,
|
||||
body,
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
// 6) parse
|
||||
const ctype = res.headers.get("content-type") ?? "";
|
||||
const isJson = ctype.includes("application/json");
|
||||
const rawText = await res.text().catch(() => "");
|
||||
const parsed: unknown = options.expectText
|
||||
? rawText
|
||||
: isJson
|
||||
? rawText
|
||||
? JSON.parse(rawText)
|
||||
: null
|
||||
: rawText;
|
||||
|
||||
// 7) error (HTTP status 에러)
|
||||
if (!res.ok) {
|
||||
const autoLogout = options.autoLogoutOnAuthError ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? true;
|
||||
|
||||
// 401 훅 호출 (기존 동작 유지)
|
||||
if (res.status === 401) options.onAuthError?.();
|
||||
|
||||
// 401 또는 403 (토큰 만료 포함) 시 자동 로그아웃 처리
|
||||
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
|
||||
// 사용자 알림은 띄우지 않고 바로 로그아웃 라우팅으로 이동
|
||||
try {
|
||||
window.location.replace("/logout");
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
// 이후 로직 진행을 막기 위해 에러를 던지기
|
||||
throw new HttpError(res.status, parsed, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
if (!suppressAlert && typeof window !== "undefined") {
|
||||
const serverMsg =
|
||||
typeof parsed === "object" &&
|
||||
parsed !== null &&
|
||||
"message" in parsed
|
||||
? String((parsed as { message?: unknown }).message ?? "")
|
||||
: typeof parsed === "string"
|
||||
? parsed
|
||||
: undefined;
|
||||
|
||||
const msg =
|
||||
setErrorMessage?.(res.status, serverMsg) ??
|
||||
(serverMsg ?? `HTTP ${res.status}`);
|
||||
// eslint-disable-next-line no-alert
|
||||
alert(`[${res.status}] ${msg}`);
|
||||
}
|
||||
|
||||
throw new HttpError(res.status, parsed, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
return parsed as T;
|
||||
} catch (err: unknown) {
|
||||
let code: string | undefined;
|
||||
if (typeof err === "object" && err !== null) {
|
||||
const anyErr = err as { cause?: unknown; code?: unknown };
|
||||
|
||||
if (anyErr.cause && typeof anyErr.cause === "object") {
|
||||
const cause = anyErr.cause as { code?: unknown };
|
||||
if (typeof cause.code === "string") {
|
||||
code = cause.code;
|
||||
}
|
||||
}
|
||||
|
||||
if (!code && typeof anyErr.code === "string") {
|
||||
code = anyErr.code;
|
||||
}
|
||||
}
|
||||
|
||||
// 🔻 여기서 네트워크 레벨 에러 처리
|
||||
if (code === "ECONNREFUSED") {
|
||||
// 네트워크 연결 실패 → HttpError(404)로 변환
|
||||
throw new HttpError(
|
||||
404,
|
||||
{ message: "백엔드 서버를 찾을 수 없습니다." },
|
||||
url.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
// 그 외 에러는 그대로 던지기
|
||||
throw err;
|
||||
} finally {
|
||||
// timeout 정리
|
||||
clearTimeout(timer);
|
||||
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
|
||||
alert(`[${res.status}] ${msg}`);
|
||||
}
|
||||
};
|
||||
|
||||
// Convenience methods (all arrow functions)
|
||||
const get = <T = unknown>(
|
||||
path: string,
|
||||
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
|
||||
) => request<T>(path, { ...o, method: "GET" });
|
||||
throw new HttpError(res.status, parsed, url.toString(), res.headers);
|
||||
}
|
||||
|
||||
const post = <T = unknown>(
|
||||
path: string,
|
||||
json?: unknown,
|
||||
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
|
||||
) => request<T>(path, { ...o, method: "POST", json });
|
||||
return parsed as T;
|
||||
} catch (err: unknown) {
|
||||
// ✅ 추가: 타임아웃/abort를 408로 매핑
|
||||
if (isAbortError(err)) {
|
||||
throw new HttpError(
|
||||
408,
|
||||
{ message: "요청 시간이 초과되었습니다.", timeoutMs: options.timeoutMs ?? defaultTimeoutMs },
|
||||
url.toString()
|
||||
);
|
||||
}
|
||||
|
||||
const put = <T = unknown>(
|
||||
path: string,
|
||||
json?: unknown,
|
||||
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
|
||||
) => request<T>(path, { ...o, method: "PUT", json });
|
||||
let code: string | undefined;
|
||||
if (typeof err === "object" && err !== null) {
|
||||
const anyErr = err as { cause?: unknown; code?: unknown };
|
||||
|
||||
const del = <T = unknown>(
|
||||
path: string,
|
||||
o?: Omit<RequestOptions, "method">
|
||||
) => request<T>(path, { ...o, method: "DELETE" });
|
||||
if (anyErr.cause && typeof anyErr.cause === "object") {
|
||||
const cause = anyErr.cause as { code?: unknown };
|
||||
if (typeof cause.code === "string") code = cause.code;
|
||||
}
|
||||
if (!code && typeof anyErr.code === "string") code = anyErr.code;
|
||||
}
|
||||
|
||||
const postForm = <T = unknown>(
|
||||
path: string,
|
||||
form: FormData,
|
||||
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
|
||||
) => request<T>(path, { ...o, method: "POST", form });
|
||||
if (code === "ECONNREFUSED") {
|
||||
throw new HttpError(404, { message: "백엔드 서버를 찾을 수 없습니다." }, url.toString());
|
||||
}
|
||||
|
||||
const putForm = <T = unknown>(
|
||||
path: string,
|
||||
form: FormData,
|
||||
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
|
||||
) => request<T>(path, { ...o, method: "PUT", form });
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
return { request, get, post, put, del, postForm, putForm };
|
||||
const get = <T = unknown>(path: string, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "GET" });
|
||||
|
||||
const post = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "POST", json });
|
||||
|
||||
const put = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "PUT", json });
|
||||
|
||||
const patch = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "PATCH", json });
|
||||
|
||||
const del = <T = unknown>(path: string, o?: Omit<RequestOptions, "method">) =>
|
||||
request<T>(path, { ...o, method: "DELETE" });
|
||||
|
||||
const postForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "POST", form });
|
||||
|
||||
const putForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
|
||||
request<T>(path, { ...o, method: "PUT", form });
|
||||
|
||||
return { request, get, post, put, patch, del, postForm, putForm };
|
||||
};
|
||||
|
||||
export const nextApi = createHttpClient(clientEnv.API_BASE);
|
||||
export const nextApi = createHttpClient(clientEnv.API_BASE);
|
||||
|
||||
52
src/lib/http-util.ts
Normal file
52
src/lib/http-util.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {NextResponse} from "next/server";
|
||||
import {HttpError} from "@/lib/http-client";
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
import commonConst from "@/config/commonConst";
|
||||
|
||||
export type ApiError = {
|
||||
status: number
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export const errorToResponse = (error: unknown) => {
|
||||
if (error instanceof HttpError) {
|
||||
const payload = error.data ?? { message: "서버에서 오류 응답을 받았습니다." }
|
||||
return NextResponse.json(payload, { status: error.status })
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: "서버 내부 오류가 발생했습니다." },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
const isDev = clientEnv.ENV !== "prod"
|
||||
|
||||
export const apiError = (e: unknown): ApiError => {
|
||||
if (e instanceof HttpError) {
|
||||
const d = e.data as any
|
||||
const code = typeof d?.code === "string" ? d.code : commonConst.unknownHttpError
|
||||
const message =
|
||||
(typeof d?.detail === "string" && d.detail) ||
|
||||
(typeof d?.message === "string" && d.message) ||
|
||||
(typeof d?.errMessage === "string" && d.errMessage) ||
|
||||
(typeof d === "string" && d) ||
|
||||
`HTTP ${e.status}`
|
||||
|
||||
if (isDev) {
|
||||
console.groupCollapsed(
|
||||
`[API ERROR] ${e.status}${code ? ` / ${code}` : ""}`
|
||||
)
|
||||
console.log("url:", e.url)
|
||||
if (e.traceId) console.log("traceId:", e.traceId)
|
||||
console.log("raw data:", d)
|
||||
console.groupEnd()
|
||||
}
|
||||
|
||||
return { status: e.status, code, message }
|
||||
}
|
||||
|
||||
if (isDev) console.error("[NON-HTTP ERROR]", e)
|
||||
return { status: 500, code: commonConst.noneHttpError, message: "저장에 실패했습니다." }
|
||||
}
|
||||
@@ -8,7 +8,6 @@ const createServerApi = async (rootUrl: string) => {
|
||||
|
||||
return createHttpClient(rootUrl, {
|
||||
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
|
||||
defaultTimeoutMs: 10_000,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -17,4 +17,69 @@ export function buildUrlWithParams(
|
||||
}
|
||||
if (extra) for (const [k, v] of Object.entries(extra)) if (v) qs.set(k, v);
|
||||
return `${targetPath}${qs.toString() ? `?${qs}` : ""}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const downloadFile = (blob: Blob, filename: string) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
export const downloadBase64File = (base64: string, filename: string) => {
|
||||
const byteString = atob(base64);
|
||||
const arrayBuffer = new ArrayBuffer(byteString.length);
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
for (let i = 0; i < byteString.length; i++) {
|
||||
uint8Array[i] = byteString.charCodeAt(i);
|
||||
}
|
||||
|
||||
const blob = new Blob([arrayBuffer], {
|
||||
type:
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
|
||||
downloadFile(blob, filename);
|
||||
};
|
||||
|
||||
export type DateTimeFormatOption =
|
||||
| "date" // 1-1. 날짜만
|
||||
| "dateHour" // 1-2. 날짜 + 시
|
||||
| "dateHourMin" // 1-3. 날짜 + 시 분
|
||||
| "dateTime"; // 1-4. 날짜 + 시 분 초
|
||||
|
||||
/**
|
||||
* 서버에서 받은 시간(ISO 문자열/Date/number)을 한국시간 기준으로 포맷팅
|
||||
* - 예: "2025-11-28T03:15:50Z" -> "2025-11-28 12:15:50" (KST)
|
||||
*/
|
||||
export const formatKst = (
|
||||
input: string | number | Date | null | undefined,
|
||||
opt: DateTimeFormatOption = "dateTime"
|
||||
): string => {
|
||||
if (!input) return "";
|
||||
|
||||
const d = input instanceof Date ? input : new Date(input);
|
||||
if (Number.isNaN(d.getTime())) return "";
|
||||
|
||||
// UTC -> KST(UTC+9) 변환
|
||||
const kst = new Date(d.getTime() + 9 * 60 * 60 * 1000);
|
||||
|
||||
const pad2 = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
const yyyy = kst.getUTCFullYear();
|
||||
const MM = pad2(kst.getUTCMonth() + 1);
|
||||
const dd = pad2(kst.getUTCDate());
|
||||
const HH = pad2(kst.getUTCHours());
|
||||
const mm = pad2(kst.getUTCMinutes());
|
||||
const ss = pad2(kst.getUTCSeconds());
|
||||
|
||||
if (opt === "date") return `${yyyy}-${MM}-${dd}`;
|
||||
if (opt === "dateHour") return `${yyyy}-${MM}-${dd} ${HH}`;
|
||||
if (opt === "dateHourMin") return `${yyyy}-${MM}-${dd} ${HH}:${mm}`;
|
||||
return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
|
||||
};
|
||||
11
src/store/jotai/dialog.ts
Normal file
11
src/store/jotai/dialog.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { atom } from 'jotai'
|
||||
|
||||
// 사용할 수 있는 DialogId를 타입으로 고정
|
||||
// Dialog추가 할 때만다 추가하기
|
||||
export type DialogId =
|
||||
| 'userUpsertDialog'
|
||||
| 'userUploadDialog'
|
||||
| 'listUploadDialog'
|
||||
|
||||
// 현재 열려 있는 다이얼로그 ID 리스트
|
||||
export const openDialogIdsAtom = atom<DialogId[]>([])
|
||||
@@ -6,6 +6,7 @@ export type LoginRequest = {
|
||||
export type LoginUser = {
|
||||
userId: string;
|
||||
userName: string;
|
||||
userCmpn: string;
|
||||
userTeam: string;
|
||||
userRole: number;
|
||||
};
|
||||
7
src/types/common.ts
Normal file
7
src/types/common.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export type DataVerification = {
|
||||
success: boolean;
|
||||
fieldName : string;
|
||||
errMessage: string;
|
||||
}
|
||||
|
||||
export type RouteContext = { params: Promise<{ slug?: string[] }> };
|
||||
16
src/types/role.ts
Normal file
16
src/types/role.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
export type RoleInfo = {
|
||||
/** 권한 코드 */
|
||||
roleCd: number
|
||||
/** 권한 명 */
|
||||
roleNm: string
|
||||
/** 메모 */
|
||||
memo: string
|
||||
/** 등록자 */
|
||||
regUser?: string
|
||||
/** 등록일시 */
|
||||
regDt?: string
|
||||
/** 수정자 */
|
||||
modUser?: string
|
||||
/** 수정일시 */
|
||||
modDt?: string
|
||||
}
|
||||
52
src/types/user.ts
Normal file
52
src/types/user.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
export type UserInfo = {
|
||||
/** 사용자 ID */
|
||||
userId: string
|
||||
/** 사용자 PW (목록 조회 시에는 내려오지 않을 수도 있어서 optional 권장) */
|
||||
userPw?: string
|
||||
/** 사용자 이름 */
|
||||
userName: string
|
||||
/** 사용자 소속 회사 */
|
||||
userCmpn: string
|
||||
/** 사용자 소속 팀 (기본값 S101) */
|
||||
userTeam: string
|
||||
/** 사용자 권한 코드 */
|
||||
userRole: number
|
||||
/** 메모 */
|
||||
memo?: string
|
||||
/** 등록자 (서버에서만 세팅되는 읽기 전용 성격) */
|
||||
regUser?: string
|
||||
/** 등록일시 (ISO 문자열로 내려온다고 가정) */
|
||||
regDt?: string
|
||||
/** 수정자 */
|
||||
modUser?: string
|
||||
/** 수정일시 */
|
||||
modDt?: string
|
||||
}
|
||||
|
||||
export type UserInfoSaveRequest = {
|
||||
userId: string
|
||||
userPw: string
|
||||
userName: string
|
||||
userCmpn: string
|
||||
userTeam?: string
|
||||
userRole: number
|
||||
memo?: string
|
||||
}
|
||||
|
||||
export type UserTableInfo = {
|
||||
userId: string
|
||||
userCmpn: string
|
||||
userName: string
|
||||
userRole: string
|
||||
regDt: string
|
||||
memo: string
|
||||
}
|
||||
|
||||
export type UserUploadResponse = {
|
||||
totalCount: number;
|
||||
successCount: number;
|
||||
failCount: number;
|
||||
hasErrorFile: boolean;
|
||||
errorFileName: string | null;
|
||||
errorFileBase64: string | null;
|
||||
};
|
||||
Reference in New Issue
Block a user