Files
vexplor/frontend/lib/api/user.ts
2025-08-21 09:41:46 +09:00

207 lines
5.3 KiB
TypeScript

import { API_BASE_URL } from "./client";
/**
* 사용자 관리 API 클라이언트
*/
interface ApiResponse<T> {
success: boolean;
data?: T;
message?: string;
errorCode?: string;
total?: number;
// 백엔드 호환성을 위한 추가 필드
result?: boolean;
msg?: string;
}
/**
* API 호출 공통 함수
*/
async function apiCall<T = any>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
headers: {
"Content-Type": "application/json",
...options.headers,
},
credentials: "include", // 쿠키 포함
...options,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("API 호출 오류:", error);
throw error;
}
}
/**
* 사용자 목록 조회
*/
export async function getUserList(params?: Record<string, any>) {
const searchParams = new URLSearchParams();
// 모든 검색 파라미터를 동적으로 처리
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== "") {
searchParams.append(key, String(value));
}
});
}
const queryString = searchParams.toString();
const endpoint = `/admin/users${queryString ? `?${queryString}` : ""}`;
console.log("📡 최종 API 호출 URL:", endpoint);
const response = await apiCall(endpoint);
// 전체 response 객체를 그대로 반환 (success, data, total 포함)
return response;
}
/**
* 사용자 정보 단건 조회
*/
export async function getUserInfo(userId: string) {
const response = await apiCall(`/admin/users/${userId}`);
if (response.success && response.data) {
return response.data;
}
throw new Error(response.message || "사용자 정보 조회에 실패했습니다.");
}
/**
* 사용자 등록
*/
export async function createUser(userData: any) {
const response = await apiCall("/admin/users", {
method: "POST",
body: JSON.stringify(userData),
});
// 백엔드에서 result 필드를 사용하므로 이에 맞춰 처리
if (response.result === true || response.success === true) {
return {
success: true,
message: response.msg || response.message || "사용자가 성공적으로 등록되었습니다.",
data: response,
};
}
throw new Error(response.msg || response.message || "사용자 등록에 실패했습니다.");
}
// 사용자 수정 기능 제거됨
/**
* 사용자 상태 변경
*/
export async function updateUserStatus(userId: string, status: string) {
const response = await apiCall(`/admin/users/${userId}/status`, {
method: "PUT",
body: JSON.stringify({ status }),
});
return response;
}
// 사용자 삭제 기능 제거됨
// 사용자 변경이력 조회
export async function getUserHistory(userId: string, params?: Record<string, any>) {
const searchParams = new URLSearchParams();
// 기본 페이지네이션 파라미터
searchParams.append("page", String(params?.page || 1));
searchParams.append("countPerPage", String(params?.countPerPage || 10));
// 추가 파라미터가 있으면 추가
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (key !== "page" && key !== "countPerPage" && value !== undefined && value !== null && value !== "") {
searchParams.append(key, String(value));
}
});
}
const queryString = searchParams.toString();
const endpoint = `/admin/users/${userId}/history${queryString ? `?${queryString}` : ""}`;
console.log("📡 사용자 변경이력 API 호출 URL:", endpoint);
const response = await apiCall(endpoint);
return response;
}
/**
* 사용자 비밀번호 초기화
*/
export async function resetUserPassword(resetData: { userId: string; newPassword: string }) {
const response = await apiCall("/admin/users/reset-password", {
method: "POST",
body: JSON.stringify(resetData),
});
return response;
}
/**
* 회사 목록 조회 (기존 API 활용)
*/
export async function getCompanyList() {
const response = await apiCall("/admin/companies");
if (response.success && response.data) {
return response.data;
}
throw new Error(response.message || "회사 목록 조회에 실패했습니다.");
}
/**
* 부서 목록 조회
*/
export async function getDepartmentList(companyCode?: string) {
const params = companyCode ? `?companyCode=${encodeURIComponent(companyCode)}` : "";
const response = await apiCall(`/admin/departments${params}`);
if (response.success && response.data) {
return response.data;
}
throw new Error(response.message || "부서 목록 조회에 실패했습니다.");
}
/**
* 사용자 ID 중복 체크
*/
export async function checkDuplicateUserId(userId: string) {
const response = await apiCall("/admin/users/check-duplicate", {
method: "POST",
body: JSON.stringify({ userId }),
});
return response;
}
// 사용자 API 객체로 export
export const userAPI = {
getList: getUserList,
getInfo: getUserInfo,
create: createUser,
updateStatus: updateUserStatus,
getHistory: getUserHistory,
resetPassword: resetUserPassword,
getCompanyList: getCompanyList,
getDepartmentList: getDepartmentList,
checkDuplicateId: checkDuplicateUserId,
};