260303_01_ENH: TanStack Query 적용
This commit is contained in:
@@ -1,138 +1,137 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState} from "react";
|
||||
import { useMemo, 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 "../../../../../components/table-column/UserTableColumn";
|
||||
import _ from "lodash";
|
||||
import { getUserColumns } from "@/components/table-column/UserTableColumn";
|
||||
import UserUpsertDialog from "@/components/dialog/UserUpsertDialog";
|
||||
import {UserInfo, UserInfoSaveRequest, UserUploadResponse} from "@/types/user";
|
||||
import {UserInfo, UserInfoSaveRequest} from "@/types/user";
|
||||
import UserUploadDialog from "@/components/dialog/UserUploadDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {downloadBase64File, downloadFile} 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 {useAuth} from "@/hooks/useAuth";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {DEFAULT_COMPANY_NAME, EXTERNAL_USER_ROLE} from "@/const/userConst";
|
||||
import {
|
||||
useRoleListQuery,
|
||||
useUserCompaniesQuery,
|
||||
useUsersQuery,
|
||||
useUserDetailQuery,
|
||||
useCheckUserIdDuplicateMutation,
|
||||
useUpsertUserMutation,
|
||||
useDeleteUserMutation,
|
||||
useUploadUsersExcelMutation,
|
||||
useDownloadUserExcelTemplateMutation,
|
||||
} from "@/query/user";
|
||||
|
||||
const UserManagePage = () => {
|
||||
const { showDialog } = useDialog();
|
||||
const mounted = useMounted();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { auth } = useAuth();
|
||||
|
||||
const [userList, setUserList] = useState<UserInfo[]>([]);
|
||||
const [viewList, setViewList] = useState<UserInfo[]>([]);
|
||||
const [selectedUserArray, setSelectedUserArray] = useState<UserInfo[]>([]);
|
||||
const [userCmpnArray, setUserCmpnArray] = useState<string[]>([]);
|
||||
const [userRoleArray, setUserRoleArray] = useState<MultiSelectOption[]>([]);
|
||||
const { auth } = useAuth();
|
||||
const roleQuery = useRoleListQuery();
|
||||
const cmpnQuery = useUserCompaniesQuery();
|
||||
const usersQuery = useUsersQuery();
|
||||
|
||||
const checkDupMutation = useCheckUserIdDuplicateMutation();
|
||||
const upsertMutation = useUpsertUserMutation();
|
||||
const deleteMutation = useDeleteUserMutation();
|
||||
const uploadMutation = useUploadUsersExcelMutation();
|
||||
const downloadTemplateMutation = useDownloadUserExcelTemplateMutation();
|
||||
|
||||
const [editUserId, setEditUserId] = useState<string | null>(null);
|
||||
const userDetailQuery = useUserDetailQuery(editUserId ?? "", !!editUserId);
|
||||
|
||||
const userRoleArray: MultiSelectOption[] = useMemo(() => {
|
||||
const roles = roleQuery.data ?? [];
|
||||
return roles.map((r) => ({ value: String(r.roleCd), label: r.roleNm }));
|
||||
}, [roleQuery.data]);
|
||||
|
||||
const userCmpnArray = cmpnQuery.data ?? [];
|
||||
const userList = usersQuery.data ?? [];
|
||||
|
||||
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 viewList = useMemo(() => {
|
||||
let temp = userList;
|
||||
|
||||
const cmpnList = await nextApi.get<string[]>("/user/cmpn");
|
||||
setUserCmpnArray(cmpnList);
|
||||
const keyword = searchText.trim();
|
||||
if (keyword) {
|
||||
const kw = keyword.toLowerCase();
|
||||
temp = temp.filter((row) =>
|
||||
[row.userId, row.userName].some((v) => (v ?? "").toLowerCase().includes(kw))
|
||||
);
|
||||
}
|
||||
|
||||
const userData = await nextApi.get<UserInfo[]>("/user");
|
||||
setUserList(userData);
|
||||
}
|
||||
if (searchCmpn.length > 0) {
|
||||
temp = temp.filter((row) => searchCmpn.includes(row.userCmpn));
|
||||
}
|
||||
|
||||
if (searchRole.length > 0) {
|
||||
temp = temp.filter((row) => searchRole.includes(String(row.userRole)));
|
||||
}
|
||||
|
||||
return temp;
|
||||
}, [userList, searchText, searchCmpn, searchRole]);
|
||||
|
||||
// 등록 버튼 클릭
|
||||
const handleCreateClick = () => {
|
||||
setDialogMode('create');
|
||||
setEditData(undefined);
|
||||
showDialog('userUpsertDialog');
|
||||
}
|
||||
setDialogMode("create");
|
||||
setEditUserId(null);
|
||||
showDialog("userUpsertDialog");
|
||||
};
|
||||
|
||||
// 중복 체크
|
||||
const handleCheckDuplicate = async (userId: string): Promise<DataVerification> => {
|
||||
return nextApi.get<DataVerification>("/user/check-user-id", {
|
||||
query: { userId },
|
||||
});
|
||||
}
|
||||
const handleCheckDuplicate = (userId: string) => {
|
||||
return checkDupMutation.mutateAsync(userId);
|
||||
};
|
||||
|
||||
|
||||
const handleSubmit = async (data: UserInfoSaveRequest): Promise<void> => {
|
||||
if (dialogMode === 'create') {
|
||||
await nextApi.put<void>("/user", data);
|
||||
await upsertMutation.mutateAsync({ mode: dialogMode, data });
|
||||
|
||||
if (dialogMode === "create") {
|
||||
alert("등록 됐습니다.");
|
||||
} else {
|
||||
await nextApi.patch<void>("/user", data);
|
||||
alert("수정 됐습니다.");
|
||||
}
|
||||
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);
|
||||
});
|
||||
// 수정 로직 또는 모달 열기
|
||||
}
|
||||
setDialogMode("edit");
|
||||
setEditUserId(userId);
|
||||
showDialog("userUpsertDialog");
|
||||
};
|
||||
|
||||
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 handleDelete = async (userId: string) => {
|
||||
if (!confirm("정말 삭제하시겠습니까?")) return;
|
||||
|
||||
await deleteMutation.mutateAsync(userId);
|
||||
alert("삭제 됐습니다.");
|
||||
};
|
||||
|
||||
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);
|
||||
const res = await uploadMutation.mutateAsync(file);
|
||||
|
||||
if (res.hasErrorFile && res.errorFileBase64) {
|
||||
downloadBase64File(res.errorFileBase64, res.errorFileName ?? "error.xlsx");
|
||||
}
|
||||
else{
|
||||
await setUserData();
|
||||
alert(`${res.successCount}개의 계정을 생성했습니다.`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const downloadTemplate = async () => {
|
||||
const buffer = await nextApi.post<ArrayBuffer>(
|
||||
"/user/excel-template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
const buffer = await downloadTemplateMutation.mutateAsync();
|
||||
|
||||
if (buffer.byteLength > 0) {
|
||||
const blob = new Blob([buffer], {
|
||||
@@ -143,7 +142,7 @@ const UserManagePage = () => {
|
||||
} else {
|
||||
console.log("빈 파일입니다.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const columns = getUserColumns(
|
||||
{
|
||||
@@ -153,30 +152,6 @@ const UserManagePage = () => {
|
||||
userRoleArray
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(setUserData);
|
||||
}, []);
|
||||
|
||||
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(String(row.userRole)));
|
||||
}
|
||||
|
||||
setViewList(tempData);
|
||||
}, [searchText, searchCmpn, searchRole, userList]);
|
||||
|
||||
const isInternal =
|
||||
mounted &&
|
||||
auth.user?.userRole != null &&
|
||||
@@ -240,7 +215,6 @@ const UserManagePage = () => {
|
||||
data={viewList}
|
||||
isClient={true}
|
||||
selectMode='single'
|
||||
onRowSelectionChange={setSelectedUserArray}
|
||||
defaultPageSize={10}
|
||||
pageSizeOptions={[10, 20, 30, 50]}
|
||||
getRowId={(row) => row.userId} // row.id = userId
|
||||
@@ -249,7 +223,7 @@ const UserManagePage = () => {
|
||||
|
||||
<UserUpsertDialog
|
||||
mode={dialogMode}
|
||||
initialData={editData}
|
||||
initialData={dialogMode === "edit" ? (userDetailQuery.data ?? undefined) : undefined}
|
||||
isInternal={isInternal}
|
||||
userCmpn={userCmpn}
|
||||
userCmpnArray={userCmpnArray}
|
||||
|
||||
@@ -1,57 +1,90 @@
|
||||
'use client'
|
||||
import {useEffect, useRef, useState} from "react";
|
||||
import {useMemo, useState} from "react";
|
||||
import BodyTitle from "@/components/layout/BodyTitle";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {getProjectColumns} from "../../../components/table-column/ProjectTableColumn";
|
||||
import {getProjectColumns} from "@/components/table-column/ProjectTableColumn";
|
||||
import {
|
||||
ProjectCreateRequest,
|
||||
ProjectInfo,
|
||||
ProjectListQuery,
|
||||
ProjectListRequest, ProjectOwnerResponse,
|
||||
ProjectStatus
|
||||
} from "@/types/project";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {PaginationState, SortingState} from "@tanstack/react-table";
|
||||
import {PageRequest, PageResponse} from "@/types/common";
|
||||
import ProjectCreateDialog from "@/components/dialog/ProjectCreateDialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {SelectedProject} from "@/store/jotai/project";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {FW_USER_ROLE} from "@/const/userConst";
|
||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {useCreateProjectMutation, useProjectListQuery, useProjectOwnerListQuery} from "@/query/project";
|
||||
import {PROJECT_STATUS_LABEL} from "@/const/projectConst";
|
||||
|
||||
const MainPage = () => {
|
||||
const router = useRouter();
|
||||
|
||||
const mounted = useMounted();
|
||||
const { users, isLoading } = useItrntUserList();
|
||||
const { showDialog } = useDialog();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const mounted = useMounted();
|
||||
const { auth } = useAuth();
|
||||
const { clearSelectedProject, setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [statusArray, setStatusArray] = useState<MultiSelectOption[]>([]);
|
||||
const [deptArray, setDeptArray] = useState<string[]>([]);
|
||||
const [fwArray, setFwArray] = useState<string[]>([]);
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||
const { setSelectedProject } = useSelectedProject();
|
||||
|
||||
const [pagination, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10 });
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [query, setQuery] = useState<ProjectListQuery>();
|
||||
|
||||
const [viewList, setViewList] = useState<ProjectInfo[]>([]);
|
||||
const [pageCount, setPageCount] = useState(0);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
|
||||
const statusArray: MultiSelectOption[] = useMemo(() => {
|
||||
return (Object.values(ProjectStatus).filter((v) => typeof v === "number") as number[])
|
||||
.sort((a, b) => a - b)
|
||||
.map((v) => ({
|
||||
value: String(v),
|
||||
label: PROJECT_STATUS_LABEL[v as ProjectStatus],
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const enabled = mounted && !isLoading; // intranet user list 준비된 뒤에만 호출
|
||||
const ownerQuery = useProjectOwnerListQuery(enabled);
|
||||
|
||||
const deptArray = ownerQuery.data?.ownerDeptList ?? [];
|
||||
const fwArray = useMemo(() => {
|
||||
const ownerFwIDList = ownerQuery.data?.ownerFwList ?? [];
|
||||
|
||||
return ownerFwIDList.map((fwID) => ({
|
||||
value: fwID,
|
||||
label: users.find(u => u.userId === fwID)?.userNm ?? "",
|
||||
}));
|
||||
|
||||
}, [ownerQuery.data?.ownerFwList]);
|
||||
|
||||
const sort = sorting?.[0] ?? { id: "prjctIdx", desc: true as const };
|
||||
|
||||
const listQuery = useProjectListQuery({
|
||||
query,
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? "desc" : "asc",
|
||||
enabled,
|
||||
});
|
||||
|
||||
const viewList = listQuery.data?.content ?? [];
|
||||
const totalCount = listQuery.data?.totalElements ?? 0;
|
||||
const pageCount = listQuery.data?.totalPages ?? 0;
|
||||
|
||||
const createMutation = useCreateProjectMutation?.();
|
||||
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [searchStatus, setSearchStatus] = useState<string[]>([]);
|
||||
const [searchDept, setSearchDept] = useState<string[]>([]);
|
||||
const [searchFw, setSearchFw] = useState<string[]>([]);
|
||||
|
||||
const columns = getProjectColumns(users);
|
||||
const userId = auth.user?.userId ?? "";
|
||||
@@ -76,8 +109,9 @@ const MainPage = () => {
|
||||
showDialog('projectCreateDialog');
|
||||
}
|
||||
|
||||
const handleSubmit = async (data:ProjectCreateRequest): Promise<void> => {
|
||||
const projectInfo = await nextApi.put<ProjectInfo>("/project", data);
|
||||
const handleSubmit = async (data: ProjectCreateRequest): Promise<void> => {
|
||||
const projectInfo = await createMutation.mutateAsync(data);
|
||||
|
||||
setSelectedProject({
|
||||
prjctIdx: projectInfo.prjctIdx,
|
||||
prjctCd: projectInfo.prjctCd,
|
||||
@@ -87,8 +121,8 @@ const MainPage = () => {
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
} as SelectedProject);
|
||||
|
||||
window.location.href = `/project/info`;
|
||||
}
|
||||
router.push("/project/info");
|
||||
};
|
||||
|
||||
const handleClick = (projectInfo:ProjectInfo) => {
|
||||
setSelectedProject({
|
||||
@@ -100,65 +134,9 @@ const MainPage = () => {
|
||||
ownerFw: projectInfo.ownerFw,
|
||||
} as SelectedProject);
|
||||
|
||||
window.location.href = `/list/manage`;
|
||||
router.push(`/list/manage`);
|
||||
}
|
||||
|
||||
// 중복 호출 방지(초기 mount에서 pagination/sorting 콜백이 각각 한번씩 날아오는 케이스 방어)
|
||||
const lastReqKeyRef = useRef<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
const reqKey = JSON.stringify({ query, pagination, sorting});
|
||||
if (lastReqKeyRef.current === reqKey) return;
|
||||
lastReqKeyRef.current = reqKey;
|
||||
|
||||
const sort = sorting?.[0] ?? {id: "prjctIdx", desc: true};
|
||||
const pageReq: PageRequest = {
|
||||
pageIndex: pagination.pageIndex,
|
||||
pageSize: pagination.pageSize,
|
||||
sortBy: sort.id,
|
||||
sortDir: sort.desc ? "desc" : "asc"
|
||||
};
|
||||
|
||||
const searchBody: ProjectListRequest = {
|
||||
prjctText: query?.prjctText || "",
|
||||
prjctStatusList: query?.prjctStatusList || [],
|
||||
ownerDeptList: query?.ownerDeptList || [],
|
||||
ownerFwList: query?.ownerFwList || [],
|
||||
pageRequest: pageReq,
|
||||
}
|
||||
|
||||
withLoadingAsync(() =>
|
||||
nextApi.post<PageResponse<ProjectInfo>>("/project/list", searchBody)
|
||||
.then((r) => {
|
||||
setViewList(r.content);
|
||||
setTotalCount(r.totalElements);
|
||||
setPageCount(r.totalPages);
|
||||
})
|
||||
.catch(() => {
|
||||
setViewList([]);
|
||||
setTotalCount(0);
|
||||
setPageCount(0);
|
||||
})
|
||||
);
|
||||
|
||||
}, [query, pagination, sorting]);
|
||||
|
||||
useEffect(() => {
|
||||
clearSelectedProject();
|
||||
|
||||
const options: MultiSelectOption[] = Object.entries(ProjectStatus)
|
||||
.sort(([a], [b]) => Number(a) - Number(b))
|
||||
.map(([key, label]) => ({ value: key, label: String(label) }));
|
||||
|
||||
setStatusArray(options);
|
||||
|
||||
nextApi.get<ProjectOwnerResponse>("/project/owner-list")
|
||||
.then((res) => {
|
||||
setDeptArray(res.ownerDeptList);
|
||||
setFwArray(res.ownerFwList);
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!mounted || isLoading) return <LoadingOverlay force />;
|
||||
|
||||
return (
|
||||
@@ -203,6 +181,8 @@ const MainPage = () => {
|
||||
items={fwArray}
|
||||
value={searchFw}
|
||||
onChange={setSearchFw}
|
||||
getValue={(item) => item.value}
|
||||
getLabel={(item) => item.label}
|
||||
placeholder="담당 실사"
|
||||
widthClassName="w-60"
|
||||
heightClassName="h-9"
|
||||
|
||||
@@ -1,130 +1,130 @@
|
||||
'use client'
|
||||
|
||||
import {useCallback, useEffect, useMemo, useState} from 'react'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { KriSingleSelect } from '@/components/common/KriAutoComplete'
|
||||
import {ProjectInfo} from "@/types/project";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {PROJECT_SEARCH_COUNT} from "@/const/projectConst";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {UserInfo} from "@/types/user";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {KriSelect, KriSelectItem} from "@/components/common/KriSelect";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {RoleInfo} from "@/types/role";
|
||||
import {CONTACT_USER_ROLE, FW_USER_ROLE} from "@/const/userConst";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import _ from "lodash";
|
||||
import { ProjectInfo } from "@/types/project";
|
||||
import { PROJECT_SEARCH_COUNT } from "@/const/projectConst";
|
||||
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
|
||||
import { useMounted } from "@/hooks/useMounted";
|
||||
import { UserInfo } from "@/types/user";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { KriSelect, KriSelectItem } from "@/components/common/KriSelect";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { CONTACT_USER_ROLE, FW_USER_ROLE } from "@/const/userConst";
|
||||
|
||||
import {
|
||||
useFieldworkUsersQuery,
|
||||
useRoleListQuery,
|
||||
useUserCompaniesQuery,
|
||||
} from "@/query/user";
|
||||
|
||||
import {
|
||||
useAssignedFieldworkIdsQuery,
|
||||
useSaveAssignedFieldworkMutation,
|
||||
useProjectTopQuery,
|
||||
} from "@/query/project";
|
||||
|
||||
const ProjectAssignPage = () => {
|
||||
const mounted = useMounted();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const { auth } = useAuth();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
|
||||
const [projectArray, setProjectArray] = useState<ProjectInfo[]>([]);
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const fwUsersQuery = useFieldworkUsersQuery(enabled);
|
||||
const assignedIdsQuery = useAssignedFieldworkIdsQuery(prjctIdx, enabled);
|
||||
const saveAssignMutation = useSaveAssignedFieldworkMutation(prjctIdx);
|
||||
|
||||
const companyQuery = useUserCompaniesQuery();
|
||||
const roleQuery = useRoleListQuery();
|
||||
|
||||
const [searchKeyword, setSearchKeyword] = useState("");
|
||||
const debouncedKeyword = useDebouncedValue(searchKeyword, 500);
|
||||
const [sourceProject, setSourceProject] = useState<ProjectInfo>();
|
||||
const projectTopQuery = useProjectTopQuery(PROJECT_SEARCH_COUNT, debouncedKeyword, mounted);
|
||||
const projectArray = projectTopQuery.data ?? [];
|
||||
const companyArray = companyQuery.data ?? [];
|
||||
|
||||
const roleArray: KriSelectItem[] = useMemo(() => {
|
||||
const roles = roleQuery.data ?? [];
|
||||
return roles
|
||||
.filter(r => r.roleCd >= FW_USER_ROLE)
|
||||
.map(r => ({ value: String(r.roleCd), label: r.roleNm }));
|
||||
}, [roleQuery.data]);
|
||||
|
||||
const [companyArray, setCompanyArray] = useState<string[]>([]);
|
||||
const [companyFilter, setCompanyFilter] = useState<string>('');
|
||||
const [roleArray, setRoleArray] = useState<KriSelectItem[]>([]);
|
||||
const [roleFilter, setRoleFilter] = useState<KriSelectItem>();
|
||||
const [fwUserArray, setFwUserArray] = useState<UserInfo[]>([]);
|
||||
const [roleFilter, setRoleFilter] = useState<KriSelectItem | undefined>(undefined);
|
||||
const fwUserArray = fwUsersQuery.data ?? [];
|
||||
|
||||
const [originAssign, setOriginAssign] = useState<UserInfo[]>([]);
|
||||
const [assignUserArray, setAssignUserArray] = useState<UserInfo[]>([]);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
|
||||
// 선택/검색(좌/우)
|
||||
const [selectedAssignUser, setSelectedAssignUser] = useState<string[]>([]);
|
||||
const [searchAssign, setSearchAssign] = useState('');
|
||||
const debouncedAssign = useDebouncedValue(searchAssign, 500);
|
||||
|
||||
const [assignInfoString, setAssignInfoString] = useState<string>('');
|
||||
|
||||
const [ableUserArray, setAbleUserArray] = useState<UserInfo[]>([]);
|
||||
const [selectedAbleUser, setSelectedAbleUser] = useState<string[]>([]);
|
||||
const [searchAble, setSearchAble] = useState('');
|
||||
const debouncedAble = useDebouncedValue(searchAble, 500);
|
||||
|
||||
const searchTopProject = async (keyword: string) => {
|
||||
const res = await nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${PROJECT_SEARCH_COUNT}`,
|
||||
{ query: { keyword } }
|
||||
);
|
||||
|
||||
setProjectArray(res);
|
||||
};
|
||||
|
||||
const handleSelectProject = (info:ProjectInfo|null) => {
|
||||
if(info === null){
|
||||
setSourceProject(undefined)
|
||||
}
|
||||
else{
|
||||
setSourceProject(info);
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectAllLeft = (checked: boolean) => {
|
||||
if (checked) {
|
||||
setSelectedAssignUser(assignUserArray.map(u => u.userId))
|
||||
} else {
|
||||
setSelectedAssignUser([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectAllRight = (checked: boolean) => {
|
||||
if (checked) {
|
||||
setSelectedAbleUser(ableUserArray.map(u => u.userId))
|
||||
} else {
|
||||
setSelectedAbleUser([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleUnassign = (id: string) => {
|
||||
setSelectedAssignUser(prev =>
|
||||
prev.includes(id)
|
||||
? prev.filter(x => x !== id)
|
||||
: [...prev, id]
|
||||
)
|
||||
}
|
||||
|
||||
const handleToggleAssign = (id: string) => {
|
||||
setSelectedAbleUser(prev =>
|
||||
prev.includes(id)
|
||||
? prev.filter(x => x !== id)
|
||||
: [...prev, id]
|
||||
)
|
||||
}
|
||||
|
||||
const appendUserInfo = (
|
||||
userIdArray:string[],
|
||||
sourceArray:UserInfo[]
|
||||
) => {
|
||||
return sourceArray.filter(user => userIdArray.includes(user.userId));
|
||||
}
|
||||
|
||||
const resetSelect = () => {
|
||||
const resetSelect = useCallback(() => {
|
||||
setSelectedAssignUser([]);
|
||||
setSelectedAbleUser([]);
|
||||
|
||||
//검색도 초기화
|
||||
setSearchAssign('');
|
||||
setSearchAble('');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const resetSelectAndAssign = () => {
|
||||
const resetSelectAndAssign = useCallback(() => {
|
||||
resetSelect();
|
||||
setAssignUserArray(_.cloneDeep(originAssign));
|
||||
setAssignUserArray(structuredClone(originAssign));
|
||||
setDirty(false);
|
||||
}, [originAssign, resetSelect]);
|
||||
|
||||
const [sourceProject, setSourceProject] = useState<ProjectInfo | undefined>(undefined);
|
||||
const handleSelectProject = (info: ProjectInfo | null) => {
|
||||
setSourceProject(info ?? undefined);
|
||||
resetSelect();
|
||||
};
|
||||
|
||||
const sourcePrjctIdx = sourceProject?.prjctIdx ?? 0;
|
||||
const sourceAssignedIdsQuery = useAssignedFieldworkIdsQuery(
|
||||
sourcePrjctIdx,
|
||||
mounted && sourcePrjctIdx > 0
|
||||
);
|
||||
|
||||
const ableUserArray: UserInfo[] = useMemo(() => {
|
||||
if (sourcePrjctIdx > 0) {
|
||||
const ids = sourceAssignedIdsQuery.data ?? [];
|
||||
return fwUserArray.filter(u => ids.includes(u.userId));
|
||||
}
|
||||
return structuredClone(fwUserArray);
|
||||
}, [fwUserArray, sourcePrjctIdx, sourceAssignedIdsQuery.data]);
|
||||
|
||||
const handleSelectAllLeft = (checked: boolean) => {
|
||||
setSelectedAssignUser(checked ? assignView.map(u => u.userId) : []);
|
||||
};
|
||||
|
||||
const handleSelectAllRight = (checked: boolean) => {
|
||||
setSelectedAbleUser(checked ? ableView.map(u => u.userId) : []);
|
||||
};
|
||||
|
||||
const handleToggleUnassign = (id: string) => {
|
||||
setSelectedAssignUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
|
||||
};
|
||||
|
||||
const handleToggleAssign = (id: string) => {
|
||||
setSelectedAbleUser(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
|
||||
};
|
||||
|
||||
const handleCompanyChange = (v: string) => {
|
||||
resetSelectAndAssign();
|
||||
setCompanyFilter(v);
|
||||
// 필요하면 데이터도 같이 재조회/재계산 트리거
|
||||
};
|
||||
|
||||
const handleRoleChange = (item: KriSelectItem) => {
|
||||
@@ -132,170 +132,132 @@ const ProjectAssignPage = () => {
|
||||
setRoleFilter(item);
|
||||
};
|
||||
|
||||
const handleAssign = () => {
|
||||
const toAssign = ableUserArray.filter(u => selectedAbleUser.includes(u.userId));
|
||||
setAssignUserArray(prev => [...prev, ...toAssign]);
|
||||
const {
|
||||
assignBase,
|
||||
assignView,
|
||||
ableBase,
|
||||
ableView,
|
||||
} = useMemo(() => {
|
||||
const roleVal = roleFilter?.value;
|
||||
const cmpnVal = companyFilter;
|
||||
|
||||
const passBase = (u: UserInfo) =>
|
||||
(!roleVal || String(u.userRole) === roleVal) &&
|
||||
(!cmpnVal || u.userCmpn === cmpnVal);
|
||||
|
||||
const kwFilter = (u: UserInfo, k: string) =>
|
||||
u.userId.includes(k) || u.userName.includes(k);
|
||||
|
||||
// LEFT
|
||||
const _assignBase = assignUserArray.filter(passBase);
|
||||
const kAssign = debouncedAssign.trim();
|
||||
const _assignView = kAssign ? _assignBase.filter((u) => kwFilter(u, kAssign)) : _assignBase;
|
||||
|
||||
// RIGHT (exclude already assigned)
|
||||
const assignedSet = new Set(assignUserArray.map((u) => u.userId));
|
||||
const _ableBase0 = ableUserArray.filter(passBase).filter((u) => !assignedSet.has(u.userId));
|
||||
const kAble = debouncedAble.trim();
|
||||
const _ableView = kAble ? _ableBase0.filter((u) => kwFilter(u, kAble)) : _ableBase0;
|
||||
|
||||
return {
|
||||
assignBase: _assignBase,
|
||||
assignView: _assignView,
|
||||
ableBase: _ableBase0,
|
||||
ableView: _ableView,
|
||||
};
|
||||
}, [
|
||||
assignUserArray,
|
||||
ableUserArray,
|
||||
roleFilter?.value,
|
||||
companyFilter,
|
||||
debouncedAssign,
|
||||
debouncedAble,
|
||||
]);
|
||||
|
||||
const assignInfoString = useMemo(() => {
|
||||
return roleArray.map(role => {
|
||||
const cnt = originAssign.filter(u => String(u.userRole) === role.value).length;
|
||||
return `${role.label} : ${cnt}`;
|
||||
}).join(' / ');
|
||||
}, [roleArray, originAssign]);
|
||||
|
||||
const handleAssign = () => {
|
||||
const toAssign = ableView.filter(u => selectedAbleUser.includes(u.userId));
|
||||
if (toAssign.length === 0) return;
|
||||
|
||||
setAssignUserArray(prev => [...prev, ...toAssign]);
|
||||
setSelectedAbleUser([]);
|
||||
}
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
const toRemove = assignUserArray.filter(u => selectedAssignUser.includes(u.userId));
|
||||
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
|
||||
if (selectedAssignUser.length === 0) return;
|
||||
|
||||
setAssignUserArray(prev => prev.filter(u => !selectedAssignUser.includes(u.userId)));
|
||||
setSelectedAssignUser([]);
|
||||
}
|
||||
setDirty(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if(selectedProject){
|
||||
await nextApi.put(
|
||||
`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`,
|
||||
assignUserArray.map(u => u.userId)
|
||||
)
|
||||
|
||||
setOriginAssign(_.cloneDeep(assignUserArray));
|
||||
|
||||
alert("저장되었습니다.");
|
||||
}
|
||||
else{
|
||||
if (!selectedProject) {
|
||||
alert("옳지 않은 요청입니다.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const baseFiltered = useCallback((users: UserInfo[]) => {
|
||||
return users.filter(
|
||||
(u) =>
|
||||
String(u.userRole) === roleFilter?.value &&
|
||||
u.userCmpn === companyFilter
|
||||
);
|
||||
}, [roleFilter, companyFilter]);
|
||||
|
||||
const withKeyword = useCallback((users: UserInfo[], keyword: string) => {
|
||||
const k = keyword.trim();
|
||||
if (!k) return users;
|
||||
|
||||
return users.filter(
|
||||
(u) => u.userId.includes(k) || u.userName.includes(k)
|
||||
);
|
||||
}, []);
|
||||
|
||||
const assignBase = useMemo(
|
||||
() => baseFiltered(assignUserArray),
|
||||
[assignUserArray, baseFiltered]
|
||||
);
|
||||
|
||||
const assignView = useMemo(
|
||||
() => withKeyword(assignBase, debouncedAssign),
|
||||
[assignBase, debouncedAssign, withKeyword]
|
||||
);
|
||||
|
||||
const assignedIdSet = useMemo(
|
||||
() => new Set(assignUserArray.map(u => u.userId)),
|
||||
[assignUserArray]
|
||||
);
|
||||
|
||||
const ableBase = useMemo(
|
||||
() => baseFiltered(ableUserArray)
|
||||
.filter((user) => !assignedIdSet.has(user.userId)),
|
||||
[ableUserArray, baseFiltered, assignedIdSet]
|
||||
);
|
||||
|
||||
const ableView = useMemo(
|
||||
() => withKeyword(ableBase, debouncedAble)
|
||||
.filter((user) => !assignedIdSet.has(user.userId)),
|
||||
[ableBase, debouncedAble, withKeyword, assignedIdSet]
|
||||
);
|
||||
await saveAssignMutation.mutateAsync(assignUserArray.map(u => u.userId));
|
||||
setOriginAssign(structuredClone(assignUserArray));
|
||||
setDirty(false);
|
||||
alert("저장되었습니다.");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if(selectedProject){
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchTopProject(keyword);
|
||||
}
|
||||
}, [debouncedKeyword]);
|
||||
const cmpn = auth.user?.userCmpn ?? "";
|
||||
if (cmpn) setCompanyFilter(cmpn);
|
||||
}, [auth.user?.userCmpn]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
nextApi.get<UserInfo[]>("/user/fieldwork")
|
||||
.then(res => setFwUserArray(res));
|
||||
if (roleFilter) return;
|
||||
if (roleArray.length === 0) return;
|
||||
|
||||
nextApi.get<string[]>("/user/cmpn")
|
||||
.then((res) => setCompanyArray(res));
|
||||
|
||||
const roleList = await nextApi.get<RoleInfo[]>("/role")
|
||||
const roleOptionArray = roleList
|
||||
.filter(role => role.roleCd >= FW_USER_ROLE)
|
||||
.map((role) => ({
|
||||
value: String(role.roleCd),
|
||||
label: role.roleNm,
|
||||
}))
|
||||
setRoleArray(roleOptionArray);
|
||||
const contactRole = roleOptionArray.find((role) => role.value === CONTACT_USER_ROLE.toString());
|
||||
if(contactRole){
|
||||
setRoleFilter(contactRole);
|
||||
}
|
||||
})
|
||||
|
||||
}, []);
|
||||
const contactRole = roleArray.find(r => r.value === String(CONTACT_USER_ROLE));
|
||||
setRoleFilter(contactRole ?? roleArray[0]);
|
||||
}, [roleArray, roleFilter]);
|
||||
|
||||
// prjctIdx 바뀌면: 편집 상태 초기화(서버 데이터 다시 주입 받을 준비)
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
setCompanyFilter(auth.user.userCmpn || "")
|
||||
}
|
||||
}, [auth.user]);
|
||||
if (!enabled) return;
|
||||
setDirty(false);
|
||||
resetSelect();
|
||||
setOriginAssign([]);
|
||||
setAssignUserArray([]);
|
||||
}, [enabled, prjctIdx, resetSelect]);
|
||||
|
||||
// 서버 배정 ids + fwUserArray 준비되면 "초기 1회" 주입
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
if(selectedProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${selectedProject.prjctIdx}`);
|
||||
const assignUserInfoArray = appendUserInfo(res, fwUserArray);
|
||||
if (!enabled) return;
|
||||
if (dirty) return;
|
||||
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(assignUserInfoArray);
|
||||
}else{
|
||||
setAssignUserArray([]);
|
||||
setOriginAssign([]);
|
||||
}
|
||||
resetSelect();
|
||||
});
|
||||
}, [fwUserArray, selectedProject, roleArray]);
|
||||
const ids = assignedIdsQuery.data;
|
||||
if (!ids) return;
|
||||
|
||||
useEffect(() => {
|
||||
const assignString = roleArray.map((role) => {
|
||||
const assignCount = originAssign.filter(user => user.userRole.toString() === role.value).length
|
||||
return `${role.label} : ${assignCount}`;
|
||||
}).join(' / ');
|
||||
// fwUserArray가 아직 비어있을 수 있으니 둘 다 준비된 상태에서만
|
||||
if (!fwUserArray || fwUserArray.length === 0) return;
|
||||
|
||||
setAssignInfoString(assignString);
|
||||
}, [originAssign]);
|
||||
const assignUserInfoArray = fwUserArray.filter(u => ids.includes(u.userId));
|
||||
setAssignUserArray(assignUserInfoArray);
|
||||
setOriginAssign(structuredClone(assignUserInfoArray));
|
||||
resetSelect();
|
||||
}, [enabled, dirty, assignedIdsQuery.data, fwUserArray, resetSelect]);
|
||||
|
||||
useEffect(() => {
|
||||
withLoadingAsync(async () => {
|
||||
let ableUserList :UserInfo[] = [];
|
||||
|
||||
if(sourceProject){
|
||||
const res = await nextApi.get<string[]>(`/assign/prjct-fieldwork/${sourceProject.prjctIdx}`);
|
||||
ableUserList = appendUserInfo(res, fwUserArray);
|
||||
}
|
||||
else{
|
||||
ableUserList = _.cloneDeep(fwUserArray);
|
||||
}
|
||||
|
||||
setAbleUserArray(ableUserList);
|
||||
});
|
||||
}, [fwUserArray, sourceProject]);
|
||||
|
||||
if (!mounted || !selectedProject) return null
|
||||
if (!mounted || !selectedProject) return null;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-1">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* 공용 필터 바 (회사 / 대상) */}
|
||||
<div className="mb-6 rounded-lg border border-gray-200 bg-white p-4 shadow-sm">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
|
||||
회사
|
||||
</div>
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">회사</div>
|
||||
<KriSelect
|
||||
items={companyArray}
|
||||
value={companyFilter}
|
||||
@@ -307,9 +269,7 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
|
||||
<div className="w-full sm:w-auto flex items-center gap-3">
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">
|
||||
대상
|
||||
</div>
|
||||
<div className="w-14 content-text-lg font-medium text-gray-700 whitespace-nowrap text-right">대상</div>
|
||||
<KriSelect
|
||||
items={roleArray}
|
||||
value={roleFilter?.value || ""}
|
||||
@@ -324,14 +284,10 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 메인 배정 영역 */}
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] gap-6 mb-6">
|
||||
{/* 왼쪽: 배정된 면접원 */}
|
||||
<div className="min-w-0">
|
||||
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15 flex items-center">
|
||||
<span className="truncate w-full">
|
||||
{assignInfoString}
|
||||
</span>
|
||||
<span className="truncate w-full">{assignInfoString}</span>
|
||||
</div>
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
|
||||
<div className="bg-gray-50 p-3 border-b border-gray-200">
|
||||
@@ -354,12 +310,13 @@ const ProjectAssignPage = () => {
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정된 {roleFilter?.label} ( {assignBase.length}명 )</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">
|
||||
배정된 {roleFilter?.label} ( {assignBase.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{assignView
|
||||
.map((userInfo) => (
|
||||
{assignView.map((userInfo) => (
|
||||
<tr
|
||||
key={userInfo.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
@@ -385,7 +342,6 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 가운데: 배정/제외 버튼 */}
|
||||
<div className="flex flex-col justify-center gap-4">
|
||||
<Button
|
||||
onClick={handleAssign}
|
||||
@@ -405,11 +361,9 @@ const ProjectAssignPage = () => {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 오른쪽: 전체 면접원 풀 */}
|
||||
<div className="min-w-0">
|
||||
<div className="p-3 bg-black text-white rounded-lg content-text-lg mb-2 h-15">
|
||||
<KriSingleSelect
|
||||
<ProjectInfo>
|
||||
<KriSingleSelect<ProjectInfo>
|
||||
items={projectArray}
|
||||
value={String(sourceProject?.prjctIdx ?? "")}
|
||||
onChange={() => {}}
|
||||
@@ -449,12 +403,13 @@ const ProjectAssignPage = () => {
|
||||
className="border-white"
|
||||
/>
|
||||
</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">배정 가능 {roleFilter?.label} ({ableBase.length}명 )</th>
|
||||
<th className="p-3 text-left content-text-base font-medium">
|
||||
배정 가능 {roleFilter?.label} ({ableBase.length}명 )
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ableView
|
||||
.map((user) => (
|
||||
{ableView.map((user) => (
|
||||
<tr
|
||||
key={user.userId}
|
||||
className={`border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
|
||||
@@ -481,7 +436,6 @@ const ProjectAssignPage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 하단 저장 버튼 */}
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import {useEffect, useState, useCallback, useRef} from 'react'
|
||||
import {useEffect, useState, useCallback, useRef, useMemo} from 'react'
|
||||
import BodyTitle from '@/components/layout/BodyTitle'
|
||||
import {Button} from '@/components/ui/button'
|
||||
import {Input} from '@/components/ui/input'
|
||||
@@ -14,7 +14,7 @@ import ResultCodeDialog from '@/components/dialog/ResultCodeDialog'
|
||||
import {useMounted} from '@/hooks/useMounted'
|
||||
import {LoadingOverlay} from '@/components/common/LoadingOverlay'
|
||||
import {
|
||||
KonKiwiProjectInfo, ProjectInfo, ProjectUpdateRequest, ResultCode,
|
||||
ProjectInfo, ProjectUpdateRequest, ResultCode,
|
||||
ProjectStatus, ResultCodeType, SurveyType
|
||||
} from "@/types/project";
|
||||
import {
|
||||
@@ -26,13 +26,20 @@ import {
|
||||
import {MultiSelectOption} from "@/components/ui/multi-select";
|
||||
import {FW_TEAM} from "@/const/userConst";
|
||||
import {useItrntUserList} from "@/hooks/useItrntUserList";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {UserInfo} from "@/types/user";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {KriEditor} from "@/components/kri-editor";
|
||||
import _ from "lodash";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {
|
||||
useProjectInfoQuery,
|
||||
useResultCodesQuery,
|
||||
useAssignedOutsourceIdsQuery,
|
||||
useUpdateProjectMutation,
|
||||
useDeleteProjectMutation,
|
||||
useUploadScenarioImageMutation, useKartProjectListQuery,
|
||||
} from "@/query/project";
|
||||
import {useOutsourceUsersQuery} from "@/query/user";
|
||||
|
||||
const defaultProjectInfo: ProjectInfo = {
|
||||
prjctIdx: 0,
|
||||
@@ -54,80 +61,120 @@ const defaultProjectInfo: ProjectInfo = {
|
||||
|
||||
type ExternalTab = 'redirect' | 'api'
|
||||
|
||||
const baseUrl = 'https://kcont.kric.com'
|
||||
const sidParam = 'sid=${$SID}'
|
||||
|
||||
const externalUrls = {
|
||||
redirect: {
|
||||
start: `${baseUrl}/redirect/start?${sidParam}`,
|
||||
complete: `${baseUrl}/redirect/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/redirect/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/redirect/quota?${sidParam}`,
|
||||
},
|
||||
api: {
|
||||
start: `${baseUrl}/api/external/start?${sidParam}`,
|
||||
complete: `${baseUrl}/api/external/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/api/external/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/api/external/quota?${sidParam}`,
|
||||
},
|
||||
} as const
|
||||
|
||||
const internalSurvey = new Set([SurveyType.KON, SurveyType.KIWI]);
|
||||
|
||||
const ProjectInfoPage = () => {
|
||||
const router = useRouter();
|
||||
const mounted = useMounted();
|
||||
const { selectedProject } = useSelectedProject();
|
||||
const { isDialogOpen, showDialog, hideDialog } = useDialog();
|
||||
const { users, isLoading } = useItrntUserList();
|
||||
const { auth } = useAuth();
|
||||
const {selectedProject} = useSelectedProject();
|
||||
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
||||
const {users} = useItrntUserList();
|
||||
const {auth} = useAuth();
|
||||
|
||||
const [projectInfo, setProjectInfo] = useState<ProjectInfo>(defaultProjectInfo);
|
||||
const [outsourceUserArray, setOutsourceUserArray] = useState<string[]>([]);
|
||||
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
||||
const [changeResultCodeType, setChangeResultCodeType] = useState<ResultCodeType[]>([]);
|
||||
|
||||
const [outsourceOptionArray, setOutsourceOptionArray] = useState<MultiSelectOption[]>([]);
|
||||
const [deptArray, setDeptArray] = useState<string[]>([]);
|
||||
const [fwArray, setFwArray] = useState<MultiSelectOption[]>([]);
|
||||
|
||||
const [surveyKeyword, setSurveyKeyword] = useState('');
|
||||
const debouncedKeyword = useDebouncedValue(surveyKeyword, 500);
|
||||
const [surveyProjectArray, setSurveyProjectArray] = useState<KonKiwiProjectInfo[]>([]);
|
||||
|
||||
const [externalTab, setExternalTab] = useState<ExternalTab>('redirect')
|
||||
const sessionTempUrlsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const internalSurvey = [SurveyType.KON, SurveyType.KIWI];
|
||||
const baseUrl = 'https://kcont.kric.com'
|
||||
const sidParam = 'sid=${$SID}'
|
||||
|
||||
const externalUrls = {
|
||||
redirect: {
|
||||
start: `${baseUrl}/redirect/start?${sidParam}`,
|
||||
complete: `${baseUrl}/redirect/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/redirect/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/redirect/quota?${sidParam}`,
|
||||
},
|
||||
api: {
|
||||
start: `${baseUrl}/api/external/start?${sidParam}`,
|
||||
complete: `${baseUrl}/api/external/complete?${sidParam}`,
|
||||
screen: `${baseUrl}/api/external/screen?${sidParam}`,
|
||||
quota: `${baseUrl}/api/external/quota?${sidParam}`,
|
||||
},
|
||||
} as const
|
||||
|
||||
const userTeam = auth.user?.userTeam ?? "";
|
||||
const prjctIdx = selectedProject?.prjctIdx ?? 0;
|
||||
const enabled = mounted && prjctIdx > 0;
|
||||
|
||||
const searchKonKiwiPrjct = async (keyword:string): Promise<void> => {
|
||||
const surveyType = projectInfo.surveyTy ?? SurveyType.NONE;
|
||||
|
||||
if(internalSurvey.includes(surveyType) && userTeam){
|
||||
const isKiwi = surveyType === SurveyType.KON? 0 : 1;
|
||||
const res = await nextApi.get<KonKiwiProjectInfo[]>(
|
||||
`/kart/project-list/${projectInfo.itrntPrjctCd}/${userTeam}/${isKiwi}`,
|
||||
{ query: keyword ? { keyword } : {} }
|
||||
);
|
||||
const surveyTy = projectInfo.surveyTy ?? SurveyType.NONE;
|
||||
const isInternalSurvey = internalSurvey.has(surveyTy);
|
||||
const isKiwi = surveyTy === SurveyType.KON ? 0 : surveyTy === SurveyType.KIWI ? 1 : 0;
|
||||
|
||||
setSurveyProjectArray(res);
|
||||
}
|
||||
}
|
||||
// 조회 쿼리들
|
||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, enabled);
|
||||
const resultCodesQuery = useResultCodesQuery(prjctIdx, enabled);
|
||||
const outsourceUsersQuery = useOutsourceUsersQuery(enabled);
|
||||
const assignedOutsourceQuery = useAssignedOutsourceIdsQuery(prjctIdx, enabled);
|
||||
|
||||
const kartEnabled =
|
||||
mounted &&
|
||||
!!projectInfo.itrntPrjctCd &&
|
||||
!!userTeam &&
|
||||
isInternalSurvey;
|
||||
|
||||
const kartProjectListQuery = useKartProjectListQuery({
|
||||
itrntPrjctCd: projectInfo.itrntPrjctCd,
|
||||
userTeam,
|
||||
isKiwi,
|
||||
keyword: debouncedKeyword,
|
||||
enabled: kartEnabled,
|
||||
});
|
||||
|
||||
const updateMutation = useUpdateProjectMutation(prjctIdx);
|
||||
const deleteMutation = useDeleteProjectMutation(prjctIdx);
|
||||
const uploadScenarioMutation = useUploadScenarioImageMutation(prjctIdx, projectInfo.prjctCd);
|
||||
|
||||
const [resultCodeArray, setResultCodeArray] = useState<ResultCode[]>([]);
|
||||
const [outsourceUserArray, setOutsourceUserArray] = useState<string[]>([]);
|
||||
const [changeResultCodeType, setChangeResultCodeType] = useState<ResultCodeType[]>([]);
|
||||
|
||||
const outsourceOptionArray: MultiSelectOption[] = useMemo(() => {
|
||||
const arr = outsourceUsersQuery.data ?? [];
|
||||
return arr.map((u) => ({
|
||||
value: u.userId,
|
||||
label: `${u.userCmpn} / ${u.userName}(${u.userId})`,
|
||||
}));
|
||||
}, [outsourceUsersQuery.data]);
|
||||
|
||||
|
||||
const surveyProjectArray = kartProjectListQuery.data ?? [];
|
||||
|
||||
const deptArray = useMemo(() => {
|
||||
const teams = Array.from(new Set((users ?? []).map((u) => u.userTeam).filter(Boolean)));
|
||||
|
||||
if (!teams.includes("T900")) teams.push("T900"); // TFT
|
||||
|
||||
return teams.sort((a, b) => a.localeCompare(b, "ko"));
|
||||
}, [users]);
|
||||
|
||||
const fwArray: MultiSelectOption[] = useMemo(() => {
|
||||
return (users ?? [])
|
||||
.filter((u) => u.userId === projectInfo.ownerFw || u.userTeam === FW_TEAM)
|
||||
.map((u) => ({value: u.userId, label: u.userNm}));
|
||||
}, [users, projectInfo.ownerFw]);
|
||||
|
||||
const handleChange = (field: keyof ProjectInfo, value: any) => {
|
||||
setProjectInfo((prev) => ({ ...prev, [field]: value }))
|
||||
setProjectInfo((prev) => ({...prev, [field]: value}))
|
||||
}
|
||||
|
||||
const handleImageUpload = useCallback(
|
||||
async (file: File): Promise<{ url: string }> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
if (!projectInfo.prjctCd) {
|
||||
alert("프로젝트 코드가 없습니다. 잠시 후 다시 시도해주세요.");
|
||||
return {url: ""};
|
||||
}
|
||||
|
||||
const url = await nextApi.putForm<string>(`/project/senario-image/${projectInfo.prjctCd}`, formData);
|
||||
|
||||
// 이 세션에서 업로드한 temp 파일 목록에 기록
|
||||
const url = await uploadScenarioMutation.mutateAsync(file);
|
||||
sessionTempUrlsRef.current.add(url);
|
||||
|
||||
return { url }
|
||||
}, [projectInfo.prjctCd]);
|
||||
return {url};
|
||||
},
|
||||
[uploadScenarioMutation, projectInfo.prjctCd]
|
||||
);
|
||||
|
||||
const handleResultCodeClick = () => {
|
||||
showDialog('resultCodeDialog')
|
||||
@@ -139,62 +186,54 @@ const ProjectInfoPage = () => {
|
||||
return
|
||||
}
|
||||
|
||||
const updateCodeArray = _.cloneDeep(
|
||||
const updateCodeArray = structuredClone(
|
||||
resultCodeArray.filter((rc) => changeResultCodeType.includes(rc.resultCdTy))
|
||||
);
|
||||
|
||||
const requestUpdateProject:ProjectUpdateRequest = {
|
||||
const requestUpdateProject: ProjectUpdateRequest = {
|
||||
projectInfo: projectInfo,
|
||||
resultCodeList: updateCodeArray,
|
||||
assignUserIdList: outsourceUserArray,
|
||||
}
|
||||
|
||||
await nextApi.patch(`/project/${projectInfo.prjctIdx}`, requestUpdateProject);
|
||||
|
||||
await updateMutation.mutateAsync(requestUpdateProject);
|
||||
alert("저장되었습니다.");
|
||||
}
|
||||
|
||||
const handleDeleteClick = async () => {
|
||||
if (confirm('복구 할 수 없습니다. 정말 삭제 하시겠습니까?')) {
|
||||
if(!selectedProject){
|
||||
alert("옳지 않은 요청입니다.");
|
||||
}
|
||||
else{
|
||||
await nextApi.del(`/project/${selectedProject.prjctIdx}`)
|
||||
}
|
||||
|
||||
window.location.href = `/`;
|
||||
if (!confirm("복구 할 수 없습니다. 정말 삭제 하시겠습니까?")) return;
|
||||
if (!selectedProject) {
|
||||
alert("옳지 않은 요청입니다.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await deleteMutation.mutateAsync();
|
||||
router.push("/");
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if(selectedProject){
|
||||
nextApi.get<ProjectInfo>(`/project/info/${selectedProject.prjctIdx}`)
|
||||
.then((res) => setProjectInfo(res));
|
||||
|
||||
nextApi.get<ResultCode[]>(`/result-code/${selectedProject.prjctIdx}`)
|
||||
.then((res) => {setResultCodeArray(res)});
|
||||
|
||||
nextApi.get<UserInfo[]>(`/user/outsource`)
|
||||
.then((res) => {
|
||||
const outsourceOptions: MultiSelectOption[] = res
|
||||
.map(u => ({
|
||||
value: u.userId,
|
||||
label: `${u.userCmpn} / ${u.userName}(${u.userId})`,
|
||||
}));
|
||||
setOutsourceOptionArray(outsourceOptions)
|
||||
});
|
||||
|
||||
nextApi.get<string[]>(`/assign/prjct-outsource/${selectedProject.prjctIdx}`)
|
||||
.then((res) => setOutsourceUserArray(res));
|
||||
if (projectInfoQuery.data) {
|
||||
setProjectInfo(projectInfoQuery.data);
|
||||
}
|
||||
}, [selectedProject])
|
||||
}, [projectInfoQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (resultCodesQuery.data) {
|
||||
setResultCodeArray(resultCodesQuery.data);
|
||||
}
|
||||
}, [resultCodesQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (assignedOutsourceQuery.data) {
|
||||
setOutsourceUserArray(assignedOutsourceQuery.data);
|
||||
}
|
||||
}, [assignedOutsourceQuery.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (projectInfo.surveyTy !== SurveyType.EXTERNAL) {
|
||||
setExternalTab('redirect')
|
||||
|
||||
if(projectInfo.surveyPrjctCd && internalSurvey.includes(projectInfo.surveyTy || SurveyType.NONE)){
|
||||
if (projectInfo.surveyPrjctCd && internalSurvey.has(projectInfo.surveyTy || SurveyType.NONE)){
|
||||
let surveyUrl = `/project/${projectInfo.surveyPrjctCd}/INDEX.asp?${sidParam}`;
|
||||
if(projectInfo.surveyTy === SurveyType.KON){
|
||||
surveyUrl = `https://kon.kric.com` + surveyUrl
|
||||
@@ -206,32 +245,7 @@ const ProjectInfoPage = () => {
|
||||
handleChange('surveyUrl', surveyUrl)
|
||||
}
|
||||
}
|
||||
}, [projectInfo.surveyTy, projectInfo.surveyPrjctCd])
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
let userTeams = Array.from(new Set(users.map(u => u.userTeam)));
|
||||
if(!userTeams.includes("T900")){ //TFT
|
||||
userTeams.push("T900");
|
||||
}
|
||||
userTeams = userTeams.sort((a, b) => a.localeCompare(b, "ko"));
|
||||
setDeptArray(userTeams);
|
||||
}, [users]);
|
||||
|
||||
useEffect(() => {
|
||||
const userOptions: MultiSelectOption[] = users
|
||||
.filter(u => u.userId == projectInfo.ownerFw || u.userTeam == FW_TEAM)
|
||||
.map(u => ({
|
||||
value: u.userId,
|
||||
label: u.userNm,
|
||||
}));
|
||||
setFwArray(userOptions);
|
||||
}, [users, projectInfo.ownerFw]);
|
||||
|
||||
useEffect(() => {
|
||||
const keyword = debouncedKeyword.trim();
|
||||
searchKonKiwiPrjct(keyword).then();
|
||||
}, [debouncedKeyword, projectInfo.surveyTy, userTeam]);
|
||||
}, [projectInfo.surveyTy, projectInfo.surveyPrjctCd]);
|
||||
|
||||
if (!mounted) return <LoadingOverlay force />
|
||||
|
||||
|
||||
@@ -5,99 +5,67 @@ import {Button} from "@/components/ui/button";
|
||||
import {Card, CardContent, CardHeader} from "@/components/ui/card";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import React, {useEffect, useRef, useState} from "react";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import {useSearchParams} from "next/navigation";
|
||||
import {LoginUser} from "@/types/auth";
|
||||
import {useRouter, useSearchParams} from "next/navigation";
|
||||
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 {NONE_HTTP_ERROR} from "@/const/commonConst";
|
||||
import {useLoginMutation} from "@/query/auth";
|
||||
|
||||
const LoginPage = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { auth, setFromLoginResponse } = useAuth();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const typeParam = searchParams.get("type") ?? "";
|
||||
|
||||
const { auth } = useAuth();
|
||||
const loginMutation = useLoginMutation();
|
||||
|
||||
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [userId, setUserId] = useState<string>("");
|
||||
const [userPw, setUserPw] = useState<string>("");
|
||||
const [seatNum, setSeatNum] = useState<string>(getSeatNumberStorage());
|
||||
const [loginType, setLoginType] = useState<string>(getLoginTypeStorage());
|
||||
const [seatNum, setSeatNum] = useState<string>("");
|
||||
const [loginType, setLoginType] = useState<string>("");
|
||||
|
||||
const passwordInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const seatNumberInputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const tryLogin = () => {
|
||||
if(!userId){
|
||||
alert("아이디를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
if(!userPw){
|
||||
alert("PW를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
if(loginType === "call" && !seatNum){
|
||||
alert("자리번호를 입력해 주세요");
|
||||
return;
|
||||
}
|
||||
const tryLogin = async () => {
|
||||
if (!userId) return alert("아이디를 입력해 주세요");
|
||||
if (!userPw) return alert("PW를 입력해 주세요");
|
||||
if (loginType === "call" && !seatNum) return alert("자리번호를 입력해 주세요");
|
||||
|
||||
setError(null);
|
||||
const loginRequestBody = {userId, userPw};
|
||||
const loginRequestOptions = {autoLogoutOnAuthError: false};
|
||||
|
||||
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
|
||||
return withLoadingAsync(() =>
|
||||
nextApi.post<LoginUser>(
|
||||
"/login", loginRequestBody, loginRequestOptions
|
||||
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신
|
||||
try {
|
||||
setSeatNumberStorage(seatNum);
|
||||
setLoginTypeStorage(loginType);
|
||||
} catch (e) {
|
||||
// 저장 실패는 치명적이지 않으므로 콘솔 로깅만
|
||||
console.warn("Failed to persist SeatNumber to secure storage:", e);
|
||||
}
|
||||
|
||||
setFromLoginResponse(data, seatNum);
|
||||
}).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 === NONE_HTTP_ERROR) {
|
||||
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
}
|
||||
else {
|
||||
setError(`로그인에 실패했습니다. (status: ${err.status})`);
|
||||
}
|
||||
})
|
||||
);
|
||||
try {
|
||||
await loginMutation.mutateAsync({ userId, userPw, seatNum, loginType });
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
if (err.status === 401 || err.status === 403) setError("아이디 또는 비밀번호를 다시 확인해주세요.");
|
||||
else if (err.code === NONE_HTTP_ERROR) setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
|
||||
else setError(`로그인에 실패했습니다. (status: ${err.status})`);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if(auth.user){
|
||||
window.location.replace("/");
|
||||
router.replace("/");
|
||||
}
|
||||
}, [auth.user]);
|
||||
|
||||
// URL 쿼리 파라미터에서 type 수신
|
||||
useEffect(() => {
|
||||
const typeParam = searchParams.get("type") ?? "";
|
||||
let seatNumTemp = "";
|
||||
|
||||
if(typeParam === "call") {
|
||||
seatNumTemp = getSeatNumberStorage();
|
||||
}
|
||||
setSeatNum(seatNumTemp);
|
||||
setLoginType(typeParam);
|
||||
}, [searchParams]);
|
||||
|
||||
if (typeParam === "call") {
|
||||
setSeatNum(getSeatNumberStorage() ?? "");
|
||||
} else {
|
||||
setSeatNum("");
|
||||
}
|
||||
|
||||
}, [typeParam]);
|
||||
|
||||
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
@@ -202,6 +170,7 @@ const LoginPage = () => {
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full mt-6 h-11"
|
||||
disabled={loginMutation.isPending}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
tryLogin();
|
||||
|
||||
@@ -1,49 +1,21 @@
|
||||
'use client'
|
||||
import { useLogoutMutation } from "@/query/auth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import {useSelectedProject} from "@/hooks/useSelectedProject";
|
||||
import {useStorage} from "@/hooks/useStorage";
|
||||
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";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const LogoutPage = () => {
|
||||
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
|
||||
const { auth, logout } = useAuth();
|
||||
const { clearSelectedProject } = useSelectedProject();
|
||||
const { withLoadingAsync } = useLoading();
|
||||
const router = useRouter();
|
||||
const logoutMutation = useLogoutMutation();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
const runLogout = async () => {
|
||||
const userId = auth.user?.userId ?? "";
|
||||
clearSelectedProject();
|
||||
logout();
|
||||
|
||||
try {
|
||||
if(userId !== ""){
|
||||
const logoutRequestOptions = {autoLogoutOnAuthError: false};
|
||||
await nextApi.post(`/logout/${userId}`, null, logoutRequestOptions);
|
||||
}
|
||||
} catch (e) {
|
||||
const err = apiError(e);
|
||||
console.error(err.status, err.code, err.message);
|
||||
}
|
||||
|
||||
const loginType = getLoginTypeStorage();
|
||||
const loginUrl = loginType === "call" ? "/login?type=call" : "/login";
|
||||
|
||||
router.replace(loginUrl);
|
||||
};
|
||||
|
||||
withLoadingAsync(runLogout);
|
||||
(async () => {
|
||||
const { loginType } = await logoutMutation.mutateAsync();
|
||||
// 기존 로직 그대로: call 타입이면 쿼리 붙여서 이동
|
||||
router.replace(loginType === "call" ? "/login?type=call" : "/login");
|
||||
})();
|
||||
}, []);
|
||||
|
||||
// Nothing to render while redirecting
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export default LogoutPage;
|
||||
Reference in New Issue
Block a user