260303_01_ENH: TanStack Query 적용
This commit is contained in:
54
src/query/auth.ts
Normal file
54
src/query/auth.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useSelectedProject } from "@/hooks/useSelectedProject";
|
||||
import { useStorage } from "@/hooks/useStorage";
|
||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||
import type { LoginUser } from "@/types/auth";
|
||||
|
||||
export const useLoginMutation = () => {
|
||||
const { setFromLoginResponse } = useAuth();
|
||||
const { set: setSeat } = useStorage(StorageKeys.SeatNumber);
|
||||
const { set: setLoginType } = useStorage(StorageKeys.LoginType);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (v: { userId: string; userPw: string; seatNum: string; loginType: string }) => {
|
||||
return nextApi.post<LoginUser>("/login", { userId: v.userId, userPw: v.userPw }, { autoLogoutOnAuthError: false });
|
||||
},
|
||||
onSuccess: (data, v) => {
|
||||
try {
|
||||
setSeat(v.seatNum);
|
||||
setLoginType(v.loginType);
|
||||
} catch {}
|
||||
setFromLoginResponse(data, v.seatNum);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const useLogoutMutation = () => {
|
||||
const qc = useQueryClient();
|
||||
const { auth, logout } = useAuth();
|
||||
const { clearSelectedProject } = useSelectedProject();
|
||||
const { get: getLoginType } = useStorage(StorageKeys.LoginType);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
const userId = auth.user?.userId ?? "";
|
||||
try {
|
||||
if (userId){
|
||||
await nextApi.post(`/logout/${userId}`, null, { autoLogoutOnAuthError: false });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
return { loginType: getLoginType() };
|
||||
},
|
||||
onSettled: () => {
|
||||
clearSelectedProject();
|
||||
logout();
|
||||
qc.clear(); // 다음 사용자/세션에 서버상태 남지 않게
|
||||
},
|
||||
});
|
||||
}
|
||||
37
src/query/intranet.ts
Normal file
37
src/query/intranet.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import {keepPreviousData, useQuery} from "@tanstack/react-query";
|
||||
import {qk} from "@/query/keys";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {ItrntUserInfo} from "@/types/user";
|
||||
import {IntranetProjectSearchResponse, KonKiwiProjectInfo} from "@/types/project";
|
||||
|
||||
export function useIntranetProjectListQuery(keyword: string, enabled: boolean) {
|
||||
const kw = keyword.trim();
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.intranetProjectList(kw),
|
||||
queryFn: () =>
|
||||
nextApi.get<IntranetProjectSearchResponse[]>(
|
||||
`/intranet/project`,
|
||||
{ query: kw ? { keyword: kw } : {} }
|
||||
),
|
||||
enabled: enabled,
|
||||
staleTime: 0,
|
||||
placeholderData: keepPreviousData, // 검색 중 빈 배열로 깜빡임 방지
|
||||
meta: { ignoreGlobalLoading: true }, // 원하면 전역 오버레이 제외(네가 이미 메타 방식 쓰고 있었지)
|
||||
});
|
||||
}
|
||||
|
||||
export function useIntranetUsersQuery(opts?: {
|
||||
enabled?: boolean;
|
||||
initialData?: ItrntUserInfo[];
|
||||
}) {
|
||||
return useQuery({
|
||||
queryKey: qk.intranetUsers(),
|
||||
queryFn: () => nextApi.get<ItrntUserInfo[]>("/intranet/user-list"),
|
||||
enabled: opts?.enabled ?? true,
|
||||
staleTime: 10 * 60_000,
|
||||
initialData: opts?.initialData,
|
||||
});
|
||||
}
|
||||
38
src/query/keys.ts
Normal file
38
src/query/keys.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type { ChannelType } from "@/types/messageTemplate";
|
||||
|
||||
export const qk = {
|
||||
roleList: () => ["role", "list"] as const,
|
||||
userCompanies: () => ["user", "companies"] as const,
|
||||
users: () => ["user", "list"] as const,
|
||||
user: (userId: string) => ["user", "detail", userId] as const,
|
||||
|
||||
fieldworkUsers: () => ["user", "fieldwork"] as const,
|
||||
outsourceUsers: () => ["user", "outsource"] as const,
|
||||
|
||||
projectTop: (count: number, keyword: string) => ["project", "top", count, keyword] as const,
|
||||
projectOwnerList: () => ["project", "owner-list"] as const,
|
||||
projectList: (
|
||||
query: unknown,
|
||||
pageIndex: number,
|
||||
pageSize: number,
|
||||
sortBy: string,
|
||||
sortDir: "asc" | "desc"
|
||||
) => ["project", "list", query, pageIndex, pageSize, sortBy, sortDir] as const,
|
||||
assignFieldwork: (prjctIdx: number) => ["assign", "prjct-fieldwork", prjctIdx] as const,
|
||||
assignOutsource: (prjctIdx: number) => ["assign", "prjct-outsource", prjctIdx] as const,
|
||||
|
||||
projectInfo: (prjctIdx: number) => ["project", "info", prjctIdx] as const,
|
||||
resultCodes: (prjctIdx: number) => ["result-code", prjctIdx] as const,
|
||||
|
||||
kartProjectList: (itrntPrjctCd: string, userTeam: string, isKiwi: number, keyword: string) =>
|
||||
["kart", "project-list", itrntPrjctCd, userTeam, isKiwi, keyword] as const,
|
||||
|
||||
intranetProjectList: (keyword: string) => ["intranet", "project-list", keyword] as const,
|
||||
intranetUsers: () => ["intranet", "user-list"] as const,
|
||||
|
||||
mainTemplate: (prjctIdx: number, chnnlTy: ChannelType) =>
|
||||
["project", "main-template", prjctIdx, chnnlTy] as const,
|
||||
templateList: (chnnlTy: ChannelType, itrntPrjctCd: string) =>
|
||||
["message-template", "list", chnnlTy, itrntPrjctCd] as const,
|
||||
template: (tmplatIdx: number) => ["message-template", "detail", tmplatIdx] as const,
|
||||
} as const;
|
||||
90
src/query/message.ts
Normal file
90
src/query/message.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { qk } from "@/query/keys";
|
||||
import type { ChannelType, Template, TemplateSummary } from "@/types/messageTemplate";
|
||||
import type { ProjectMainTemplateUpdateRequest } from "@/types/project";
|
||||
|
||||
export function useTemplateListQuery(chnnlTy: ChannelType, itrntPrjctCd: string, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.templateList(chnnlTy, itrntPrjctCd),
|
||||
queryFn: () => nextApi.get<TemplateSummary[]>(`/message-template/list/${chnnlTy}/${itrntPrjctCd}`),
|
||||
enabled: enabled && !!itrntPrjctCd,
|
||||
staleTime: 30_000,
|
||||
meta: { ignoreGlobalLoading: true },
|
||||
});
|
||||
}
|
||||
|
||||
export function useMainTemplateIdxQuery(prjctIdx: number, chnnlTy: ChannelType, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.mainTemplate(prjctIdx, chnnlTy),
|
||||
queryFn: () => nextApi.get<number | null>(`/project/main-template/${prjctIdx}/${chnnlTy}`),
|
||||
enabled: enabled && prjctIdx > 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useTemplateQuery(tmplatIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.template(tmplatIdx),
|
||||
queryFn: () => nextApi.get<Template>(`/message-template/${tmplatIdx}`),
|
||||
enabled: enabled && tmplatIdx > 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
// meta: { ignoreGlobalLoading: true },
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveTemplateMutation(chnnlTy: ChannelType, itrntPrjctCd: string) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (v: { method: "put" | "patch"; template: Template }) => {
|
||||
const { method, template } = v;
|
||||
return method === "put"
|
||||
? nextApi.put<Template>(`/message-template`, template)
|
||||
: nextApi.patch<Template>(`/message-template`, template);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
if (res.tmplatIdx) {
|
||||
qc.setQueryData(qk.template(res.tmplatIdx), res);
|
||||
}
|
||||
qc.invalidateQueries({ queryKey: qk.templateList(chnnlTy, itrntPrjctCd) });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateMainTemplateMutation(prjctIdx: number, chnnlTy: ChannelType) {
|
||||
const qc = useQueryClient();
|
||||
const key = qk.mainTemplate(prjctIdx, chnnlTy);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (req: ProjectMainTemplateUpdateRequest) => {
|
||||
await nextApi.patch(`/project/main-template`, req);
|
||||
return req.tmplatIdx ?? null;
|
||||
},
|
||||
onMutate: async (req) => {
|
||||
const prev = qc.getQueryData<number | null>(key) ?? null;
|
||||
qc.setQueryData<number | null>(key, req.tmplatIdx ?? null);
|
||||
return { prev };
|
||||
},
|
||||
onError: (_err, _req, ctx) => {
|
||||
if (ctx?.prev !== undefined) qc.setQueryData<number | null>(key, ctx.prev);
|
||||
},
|
||||
onSettled: () => {
|
||||
qc.invalidateQueries({ queryKey: key });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadTemplateBodyImageMutation(itrntPrjctCd: string) {
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<string> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return nextApi.putForm<string>(`/message-template/body-image/${itrntPrjctCd}`, formData);
|
||||
},
|
||||
});
|
||||
}
|
||||
230
src/query/project.ts
Normal file
230
src/query/project.ts
Normal file
@@ -0,0 +1,230 @@
|
||||
"use client";
|
||||
|
||||
import {useQuery, keepPreviousData, useQueryClient, useMutation} from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { qk } from "@/query/keys";
|
||||
import type {
|
||||
KonKiwiProjectInfo,
|
||||
ProjectCreateRequest,
|
||||
ProjectInfo,
|
||||
ProjectListQuery,
|
||||
ProjectListRequest,
|
||||
ProjectOwnerResponse, ProjectUpdateRequest, ResultCode
|
||||
} from "@/types/project";
|
||||
import {PageRequest, PageResponse} from "@/types/common";
|
||||
|
||||
export function useProjectOwnerListQuery(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.projectOwnerList(),
|
||||
queryFn: () => nextApi.get<ProjectOwnerResponse>("/project/owner-list"),
|
||||
enabled,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export type ProjectListArgs = {
|
||||
query?: ProjectListQuery;
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
sortBy?: string;
|
||||
sortDir?: "asc" | "desc";
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
export function useProjectListQuery(args: ProjectListArgs, ignoreGlobalLoading: boolean = false) {
|
||||
const {
|
||||
query,
|
||||
pageIndex,
|
||||
pageSize,
|
||||
sortBy = "prjctIdx",
|
||||
sortDir = "desc",
|
||||
enabled = true,
|
||||
} = args;
|
||||
|
||||
const pageReq: PageRequest = { pageIndex, pageSize, sortBy, sortDir };
|
||||
|
||||
const body: ProjectListRequest = {
|
||||
prjctText: query?.prjctText || "",
|
||||
prjctStatusList: query?.prjctStatusList || [],
|
||||
ownerDeptList: query?.ownerDeptList || [],
|
||||
ownerFwList: query?.ownerFwList || [],
|
||||
pageRequest: pageReq,
|
||||
};
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.projectList(body, pageIndex, pageSize, sortBy, sortDir),
|
||||
queryFn: () => nextApi.post<PageResponse<ProjectInfo>>("/project/list", body),
|
||||
enabled,
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
placeholderData: keepPreviousData, // 페이지/정렬 바뀔 때 빈 배열로 깜빡임 방지
|
||||
meta: { ignoreGlobalLoading: ignoreGlobalLoading },
|
||||
});
|
||||
}
|
||||
|
||||
export function useProjectTopQuery(count: number, keyword: string, enabled: boolean) {
|
||||
const kw = keyword.trim();
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.projectTop(count, kw),
|
||||
queryFn: () =>
|
||||
nextApi.get<ProjectInfo[]>(
|
||||
`/project/top/${count}`,
|
||||
{ query: { keyword: kw } }
|
||||
),
|
||||
enabled,
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
placeholderData: keepPreviousData,
|
||||
meta: { ignoreGlobalLoading: true },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트 상세
|
||||
* - "자동 호출"은 아니고, 화면 들어올 때 최신 1회 확보 용도로 staleTime 0 + refetchOnMount always
|
||||
*/
|
||||
export function useProjectInfoQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.projectInfo(prjctIdx),
|
||||
queryFn: () => nextApi.get<ProjectInfo>(`/project/info/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 결과 코드 목록
|
||||
*/
|
||||
export function useResultCodesQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.resultCodes(prjctIdx),
|
||||
queryFn: () => nextApi.get<ResultCode[]>(`/result-code/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useKartProjectListQuery(args: {
|
||||
itrntPrjctCd: string;
|
||||
userTeam: string;
|
||||
isKiwi: number; // KON=0, KIWI=1
|
||||
keyword: string;
|
||||
enabled: boolean;
|
||||
}) {
|
||||
const kw = args.keyword.trim();
|
||||
|
||||
return useQuery({
|
||||
queryKey: qk.kartProjectList(args.itrntPrjctCd, args.userTeam, args.isKiwi, kw),
|
||||
queryFn: () =>
|
||||
nextApi.get<KonKiwiProjectInfo[]>(
|
||||
`/kart/project-list/${args.itrntPrjctCd}/${args.userTeam}/${args.isKiwi}`,
|
||||
{ query: kw ? { keyword: kw } : {} }
|
||||
),
|
||||
enabled: args.enabled,
|
||||
staleTime: 0,
|
||||
placeholderData: keepPreviousData, // 검색 중 빈 배열로 깜빡임 방지
|
||||
meta: { ignoreGlobalLoading: true }, // 원하면 전역 오버레이 제외(네가 이미 메타 방식 쓰고 있었지)
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트에 배정된 외주 userId 목록
|
||||
*/
|
||||
export function useAssignedOutsourceIdsQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.assignOutsource(prjctIdx),
|
||||
queryFn: () => nextApi.get<string[]>(`/assign/prjct-outsource/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssignedFieldworkIdsQuery(prjctIdx: number, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.assignFieldwork(prjctIdx),
|
||||
queryFn: () => nextApi.get<string[]>(`/assign/prjct-fieldwork/${prjctIdx}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateProjectMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: ProjectCreateRequest) => nextApi.put<ProjectInfo>("/project", data),
|
||||
onSuccess: () => {
|
||||
// 목록 쿼리 전부 무효화(필터/페이지/정렬이 queryKey에 들어가서 prefix로)
|
||||
qc.invalidateQueries({ queryKey: ["project", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트 수정
|
||||
*/
|
||||
export function useUpdateProjectMutation(prjctIdx: number) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (payload: ProjectUpdateRequest) =>
|
||||
nextApi.patch<void>(`/project/${prjctIdx}`, payload),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: qk.projectInfo(prjctIdx) });
|
||||
// 목록 화면도 최신화 필요하면 prefix invalidate 추가 가능
|
||||
// qc.invalidateQueries({ queryKey: ["project", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveAssignedFieldworkMutation(prjctIdx: number) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userIds: string[]) =>
|
||||
nextApi.put<void>(`/assign/prjct-fieldwork/${prjctIdx}`, userIds),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: qk.assignFieldwork(prjctIdx) });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 프로젝트 삭제
|
||||
*/
|
||||
export function useDeleteProjectMutation(prjctIdx: number) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: () => nextApi.del<void>(`/project/${prjctIdx}`),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["project", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 시나리오 이미지 업로드 (엔드포인트 spelling은 너 서버 기준으로)
|
||||
*/
|
||||
export function useUploadScenarioImageMutation(prjctIdx: number, prjctCd: string) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<string> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
|
||||
// 서버가 업로드된 이미지 URL을 문자열로 반환한다는 전제
|
||||
return await nextApi.postForm<string>(`/project/senario-image/${prjctCd}`, formData);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// 업로드 결과가 projectInfo에 반영된다면 해당 프로젝트만 갱신
|
||||
qc.invalidateQueries({ queryKey: qk.projectInfo(prjctIdx) });
|
||||
},
|
||||
});
|
||||
}
|
||||
129
src/query/user.ts
Normal file
129
src/query/user.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { qk } from "@/query/keys";
|
||||
|
||||
// 프로젝트에 존재하는 타입 기준(경로/이름 다르면 import만 수정)
|
||||
import type { RoleInfo } from "@/types/role";
|
||||
import type { UserInfo, UserInfoSaveRequest, UserUploadResponse } from "@/types/user";
|
||||
import type { DataVerification } from "@/types/common";
|
||||
|
||||
export function useRoleListQuery() {
|
||||
return useQuery({
|
||||
queryKey: qk.roleList(),
|
||||
queryFn: () => nextApi.get<RoleInfo[]>("/role"),
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserCompaniesQuery() {
|
||||
return useQuery({
|
||||
queryKey: qk.userCompanies(),
|
||||
queryFn: () => nextApi.get<string[]>("/user/cmpn"),
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useUsersQuery() {
|
||||
return useQuery({
|
||||
queryKey: qk.users(),
|
||||
queryFn: () => nextApi.get<UserInfo[]>("/user"),
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
//refetchOnWindowFocus: true, // 탭 다시 볼 때마다
|
||||
//refetchOnReconnect: true, // 네트워크 복구 시
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserDetailQuery(userId: string, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.user(userId),
|
||||
queryFn: () => nextApi.get<UserInfo>(`/user/${encodeURIComponent(userId)}`),
|
||||
enabled,
|
||||
staleTime: 0, // 항상 오래된 데이터 취급
|
||||
refetchOnMount: "always", // 컴포넌트 다시 붙을 때마다
|
||||
//refetchOnWindowFocus: true, // 탭 다시 볼 때마다
|
||||
//refetchOnReconnect: true, // 네트워크 복구 시
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 외주 사용자 목록
|
||||
*/
|
||||
export function useOutsourceUsersQuery(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.outsourceUsers(),
|
||||
queryFn: () => nextApi.get<UserInfo[]>("/user/outsource"),
|
||||
enabled,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useFieldworkUsersQuery(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: qk.fieldworkUsers(),
|
||||
queryFn: () => nextApi.get<UserInfo[]>("/user/fieldwork"),
|
||||
enabled,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCheckUserIdDuplicateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) =>
|
||||
nextApi.get<DataVerification>("/user/check-user-id", { query: { userId } }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpsertUserMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (v: { mode: "create" | "edit"; data: UserInfoSaveRequest }) => {
|
||||
return v.mode === "create"
|
||||
? nextApi.put<void>("/user", v.data)
|
||||
: nextApi.patch<void>("/user", v.data);
|
||||
},
|
||||
onSuccess: (_res, v) => {
|
||||
qc.invalidateQueries({ queryKey: qk.users() });
|
||||
|
||||
const userId = (v.data as any)?.userId;
|
||||
if (userId) {
|
||||
qc.invalidateQueries({ queryKey: qk.user(String(userId)) });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUserMutation() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) => nextApi.del<void>(`/user/${encodeURIComponent(userId)}`),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: qk.users() }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadUsersExcelMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return nextApi.postForm<UserUploadResponse>("/user/excel", formData);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
if (!res.hasErrorFile) {
|
||||
qc.invalidateQueries({ queryKey: qk.users() });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadUserExcelTemplateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
nextApi.post<ArrayBuffer>("/user/excel-template", undefined, { expectBinary: true }),
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user