회원 불러오기 작업하는 중1
This commit is contained in:
@@ -24,10 +24,27 @@ export default function CourseRegistrationModal({ open, onClose, onSave, onDelet
|
||||
const modalRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// 강사 목록 가져오기
|
||||
// TODO: 나중에 DB에서 가져오도록 변경 시 async/await 사용
|
||||
// 예: const [instructors, setInstructors] = useState<UserRow[]>([]);
|
||||
// useEffect(() => { getInstructors().then(setInstructors); }, []);
|
||||
const instructors = useMemo(() => getInstructors(), []);
|
||||
const [instructors, setInstructors] = useState<UserRow[]>([]);
|
||||
const [isLoadingInstructors, setIsLoadingInstructors] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadInstructors() {
|
||||
setIsLoadingInstructors(true);
|
||||
try {
|
||||
const data = await getInstructors();
|
||||
setInstructors(data);
|
||||
} catch (error) {
|
||||
console.error('강사 목록 로드 오류:', error);
|
||||
setInstructors([]);
|
||||
} finally {
|
||||
setIsLoadingInstructors(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (open) {
|
||||
loadInstructors();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// 선택된 강사 정보
|
||||
const selectedInstructor = useMemo(() => {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { getInstructors } from "@/app/admin/id/mockData";
|
||||
|
||||
export type Course = {
|
||||
id: string;
|
||||
courseName: string;
|
||||
@@ -12,17 +10,22 @@ export type Course = {
|
||||
// TODO: 나중에 DB에서 가져오도록 변경
|
||||
export const MOCK_CURRENT_USER = "관리자"; // 현재 로그인한 사용자 이름
|
||||
|
||||
// 강사 목록 가져오기
|
||||
const instructors = getInstructors();
|
||||
const instructorNames = instructors.map(instructor => instructor.name);
|
||||
|
||||
// TODO: 이 부분도 나중에는 db에서 받아오도록 변경 예정
|
||||
// 임시 데이터 - 강사명은 mockData.ts의 강사 데이터 활용
|
||||
// 임시 데이터 - 기본 강사명 목록 (getInstructors는 async이므로 모듈 레벨에서 사용 불가)
|
||||
const defaultInstructorNames = [
|
||||
"최예준",
|
||||
"정시우",
|
||||
"임건우",
|
||||
"송윤서",
|
||||
"김민수",
|
||||
"정대현",
|
||||
];
|
||||
|
||||
export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "1",
|
||||
courseName: "웹 개발 기초",
|
||||
instructorName: instructorNames[0] || "최예준",
|
||||
instructorName: defaultInstructorNames[0] || "최예준",
|
||||
createdAt: "2024-01-15",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -30,7 +33,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "2",
|
||||
courseName: "React 실전 프로젝트",
|
||||
instructorName: instructorNames[1] || "정시우",
|
||||
instructorName: defaultInstructorNames[1] || "정시우",
|
||||
createdAt: "2024-02-20",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -38,7 +41,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "3",
|
||||
courseName: "데이터베이스 설계",
|
||||
instructorName: instructorNames[2] || "임건우",
|
||||
instructorName: defaultInstructorNames[2] || "임건우",
|
||||
createdAt: "2024-03-10",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -46,7 +49,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "4",
|
||||
courseName: "Node.js 백엔드 개발",
|
||||
instructorName: instructorNames[3] || "송윤서",
|
||||
instructorName: defaultInstructorNames[3] || "송윤서",
|
||||
createdAt: "2024-03-25",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -54,7 +57,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "5",
|
||||
courseName: "TypeScript 마스터",
|
||||
instructorName: instructorNames[4] || "김민수",
|
||||
instructorName: defaultInstructorNames[4] || "김민수",
|
||||
createdAt: "2024-04-05",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -62,7 +65,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "6",
|
||||
courseName: "UI/UX 디자인 기초",
|
||||
instructorName: instructorNames[5] || "정대현",
|
||||
instructorName: defaultInstructorNames[5] || "정대현",
|
||||
createdAt: "2024-04-18",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -70,7 +73,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "7",
|
||||
courseName: "모바일 앱 개발",
|
||||
instructorName: instructorNames[0] || "최예준",
|
||||
instructorName: defaultInstructorNames[0] || "최예준",
|
||||
createdAt: "2024-05-02",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -78,7 +81,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "8",
|
||||
courseName: "클라우드 인프라",
|
||||
instructorName: instructorNames[1] || "정시우",
|
||||
instructorName: defaultInstructorNames[1] || "정시우",
|
||||
createdAt: "2024-05-15",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -86,7 +89,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "9",
|
||||
courseName: "머신러닝 입문",
|
||||
instructorName: instructorNames[2] || "임건우",
|
||||
instructorName: defaultInstructorNames[2] || "임건우",
|
||||
createdAt: "2024-06-01",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
@@ -94,7 +97,7 @@ export const MOCK_COURSES: Course[] = [
|
||||
{
|
||||
id: "10",
|
||||
courseName: "DevOps 실무",
|
||||
instructorName: instructorNames[3] || "송윤서",
|
||||
instructorName: defaultInstructorNames[3] || "송윤서",
|
||||
createdAt: "2024-06-20",
|
||||
createdBy: MOCK_CURRENT_USER,
|
||||
hasLessons: false,
|
||||
|
||||
@@ -10,48 +10,115 @@ export type UserRow = {
|
||||
status: AccountStatus;
|
||||
};
|
||||
|
||||
// 임시 데이터
|
||||
export const mockUsers: UserRow[] = [
|
||||
{ id: "1", joinDate: "2024-01-15", name: "김민준", email: "user1@example.com", role: "learner", status: "active" },
|
||||
{ id: "2", joinDate: "2024-01-20", name: "이서준", email: "user2@example.com", role: "learner", status: "active" },
|
||||
{ id: "3", joinDate: "2024-02-05", name: "박도윤", email: "user3@example.com", role: "learner", status: "inactive" },
|
||||
{ id: "4", joinDate: "2024-02-10", name: "최예준", email: "user4@example.com", role: "instructor", status: "active" },
|
||||
{ id: "5", joinDate: "2024-02-15", name: "정시우", email: "user5@example.com", role: "instructor", status: "active" },
|
||||
{ id: "6", joinDate: "2024-02-20", name: "강하준", email: "user6@example.com", role: "learner", status: "active" },
|
||||
{ id: "7", joinDate: "2024-03-01", name: "조주원", email: "user7@example.com", role: "admin", status: "active" },
|
||||
{ id: "8", joinDate: "2024-03-05", name: "윤지호", email: "user8@example.com", role: "learner", status: "active" },
|
||||
{ id: "9", joinDate: "2024-03-10", name: "장준서", email: "user9@example.com", role: "learner", status: "inactive" },
|
||||
{ id: "10", joinDate: "2024-03-15", name: "임건우", email: "user10@example.com", role: "instructor", status: "active" },
|
||||
{ id: "11", joinDate: "2024-03-20", name: "한서연", email: "user11@example.com", role: "learner", status: "active" },
|
||||
{ id: "12", joinDate: "2024-04-01", name: "오서윤", email: "user12@example.com", role: "learner", status: "active" },
|
||||
{ id: "13", joinDate: "2024-04-05", name: "서지우", email: "user13@example.com", role: "instructor", status: "inactive" },
|
||||
{ id: "14", joinDate: "2024-04-10", name: "신서현", email: "user14@example.com", role: "learner", status: "active" },
|
||||
{ id: "15", joinDate: "2024-04-15", name: "권민서", email: "user15@example.com", role: "admin", status: "active" },
|
||||
{ id: "16", joinDate: "2024-04-20", name: "황하은", email: "user16@example.com", role: "learner", status: "active" },
|
||||
{ id: "17", joinDate: "2024-05-01", name: "안예은", email: "user17@example.com", role: "learner", status: "inactive" },
|
||||
{ id: "18", joinDate: "2024-05-05", name: "송윤서", email: "user18@example.com", role: "instructor", status: "active" },
|
||||
{ id: "19", joinDate: "2024-05-10", name: "전채원", email: "user19@example.com", role: "learner", status: "active" },
|
||||
{ id: "20", joinDate: "2024-05-15", name: "홍지원", email: "user20@example.com", role: "learner", status: "active" },
|
||||
{ id: "21", joinDate: "2024-05-20", name: "김민수", email: "user21@example.com", role: "instructor", status: "active" },
|
||||
{ id: "22", joinDate: "2024-06-01", name: "이영희", email: "user22@example.com", role: "learner", status: "active" },
|
||||
{ id: "23", joinDate: "2024-06-05", name: "박철수", email: "user23@example.com", role: "learner", status: "inactive" },
|
||||
{ id: "24", joinDate: "2024-06-10", name: "최수진", email: "user24@example.com", role: "admin", status: "active" },
|
||||
{ id: "25", joinDate: "2024-06-15", name: "정대현", email: "user25@example.com", role: "instructor", status: "active" },
|
||||
{ id: "26", joinDate: "2024-06-20", name: "강미영", email: "user26@example.com", role: "learner", status: "active" },
|
||||
{ id: "27", joinDate: "2024-07-01", name: "조성호", email: "user27@example.com", role: "learner", status: "active" },
|
||||
{ id: "28", joinDate: "2024-07-05", name: "윤지은", email: "user28@example.com", role: "instructor", status: "inactive" },
|
||||
{ id: "29", joinDate: "2024-07-10", name: "장현우", email: "user29@example.com", role: "learner", status: "active" },
|
||||
{ id: "30", joinDate: "2024-07-15", name: "임소영", email: "user30@example.com", role: "learner", status: "active" },
|
||||
];
|
||||
// 더미 데이터 제거됨 - 이제 API에서 데이터를 가져옵니다
|
||||
|
||||
// 강사 목록 가져오기 함수 export
|
||||
// TODO: 나중에 DB에서 가져오도록 변경 예정
|
||||
// 예: export async function getInstructors(): Promise<UserRow[]> {
|
||||
// const response = await fetch('/api/instructors');
|
||||
// return response.json();
|
||||
// }
|
||||
export function getInstructors(): UserRow[] {
|
||||
// 현재는 mock 데이터 사용, 나중에 DB에서 가져오도록 변경
|
||||
return mockUsers.filter(user => user.role === 'instructor' && user.status === 'active');
|
||||
// 강사 목록 가져오기 함수 - API에서 가져오기
|
||||
export async function getInstructors(): Promise<UserRow[]> {
|
||||
try {
|
||||
const token = typeof window !== 'undefined'
|
||||
? (localStorage.getItem('token') || document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('token='))
|
||||
?.split('=')[1])
|
||||
: null;
|
||||
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_BASE_URL
|
||||
? `${process.env.NEXT_PUBLIC_API_BASE_URL}/admin/users/compact`
|
||||
: 'https://hrdi.coconutmeet.net/admin/users/compact';
|
||||
|
||||
console.log('🔍 [getInstructors] API 호출 정보:', {
|
||||
url: apiUrl,
|
||||
hasToken: !!token,
|
||||
tokenLength: token?.length || 0
|
||||
});
|
||||
|
||||
const response = await fetch(apiUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
});
|
||||
|
||||
console.log('📡 [getInstructors] API 응답 상태:', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
ok: response.ok
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error('❌ [getInstructors] API 에러 응답:', errorText);
|
||||
console.error('강사 목록 가져오기 실패:', response.status);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
console.log('📦 [getInstructors] 원본 API 응답 데이터:', {
|
||||
type: typeof data,
|
||||
isArray: Array.isArray(data),
|
||||
length: Array.isArray(data) ? data.length : 'N/A',
|
||||
data: data,
|
||||
sampleItem: Array.isArray(data) && data.length > 0 ? data[0] : null
|
||||
});
|
||||
|
||||
// API 응답 데이터를 UserRow 형식으로 변환하고 강사만 필터링 (null 값도 표시)
|
||||
const users: UserRow[] = Array.isArray(data)
|
||||
? data
|
||||
.map((user: any, index: number) => {
|
||||
// null 값을 명시적으로 처리 (null이면 "(없음)" 표시)
|
||||
const getValue = (value: any, fallback: string = '(없음)') => {
|
||||
if (value === null || value === undefined) return fallback;
|
||||
if (typeof value === 'string' && value.trim() === '') return fallback;
|
||||
return String(value);
|
||||
};
|
||||
|
||||
const transformed = {
|
||||
id: getValue(user.id || user.userId, `user-${index + 1}`),
|
||||
joinDate: getValue(user.joinDate || user.createdAt || user.join_date, new Date().toISOString().split('T')[0]),
|
||||
name: getValue(user.name || user.userName, '(없음)'),
|
||||
email: getValue(user.email || user.userEmail, '(없음)'),
|
||||
role: (user.role === 'instructor' || user.role === 'INSTRUCTOR' ? 'instructor' :
|
||||
user.role === 'admin' || user.role === 'ADMIN' ? 'admin' : 'learner') as RoleType,
|
||||
status: (user.status === 'inactive' || user.status === 'INACTIVE' ? 'inactive' : 'active') as AccountStatus,
|
||||
};
|
||||
|
||||
// 모든 항목의 null 체크
|
||||
console.log(`🔎 [getInstructors] [${index + 1}번째] 사용자 데이터 변환:`, {
|
||||
원본: user,
|
||||
변환됨: transformed,
|
||||
null체크: {
|
||||
id: user.id === null || user.id === undefined,
|
||||
userId: user.userId === null || user.userId === undefined,
|
||||
joinDate: user.joinDate === null || user.joinDate === undefined,
|
||||
createdAt: user.createdAt === null || user.createdAt === undefined,
|
||||
join_date: user.join_date === null || user.join_date === undefined,
|
||||
name: user.name === null || user.name === undefined,
|
||||
userName: user.userName === null || user.userName === undefined,
|
||||
email: user.email === null || user.email === undefined,
|
||||
userEmail: user.userEmail === null || user.userEmail === undefined,
|
||||
role: user.role === null || user.role === undefined,
|
||||
status: user.status === null || user.status === undefined,
|
||||
}
|
||||
});
|
||||
|
||||
return transformed;
|
||||
})
|
||||
.filter((user: UserRow) => user.role === 'instructor' && user.status === 'active')
|
||||
: [];
|
||||
|
||||
console.log('✅ [getInstructors] 변환된 강사 데이터:', {
|
||||
총개수: users.length,
|
||||
필터링전개수: Array.isArray(data) ? data.length : 0,
|
||||
데이터: users,
|
||||
빈배열여부: users.length === 0
|
||||
});
|
||||
|
||||
return users;
|
||||
} catch (error) {
|
||||
console.error('강사 목록 가져오기 오류:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
|
||||
import { useState, useEffect, useRef, useMemo } from "react";
|
||||
import AdminSidebar from "@/app/components/AdminSidebar";
|
||||
import DropdownIcon from "@/app/svgs/dropdownicon";
|
||||
import ChevronDownSvg from "@/app/svgs/chevrondownsvg";
|
||||
import { mockUsers, type UserRow } from "./mockData";
|
||||
import { type UserRow } from "./mockData";
|
||||
|
||||
type TabType = 'all' | 'learner' | 'instructor' | 'admin';
|
||||
type RoleType = 'learner' | 'instructor' | 'admin';
|
||||
@@ -24,7 +23,9 @@ const statusLabels: Record<AccountStatus, string> = {
|
||||
|
||||
export default function AdminIdPage() {
|
||||
const [activeTab, setActiveTab] = useState<TabType>('all');
|
||||
const [users, setUsers] = useState<UserRow[]>(mockUsers);
|
||||
const [users, setUsers] = useState<UserRow[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [openDropdownId, setOpenDropdownId] = useState<string | null>(null);
|
||||
const [isActivateModalOpen, setIsActivateModalOpen] = useState(false);
|
||||
const [isDeactivateModalOpen, setIsDeactivateModalOpen] = useState(false);
|
||||
@@ -32,10 +33,112 @@ export default function AdminIdPage() {
|
||||
const [showToast, setShowToast] = useState(false);
|
||||
const [toastMessage, setToastMessage] = useState('');
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [deactivateReason, setDeactivateReason] = useState('');
|
||||
const dropdownRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
|
||||
|
||||
const ITEMS_PER_PAGE = 10;
|
||||
|
||||
// API에서 사용자 데이터 가져오기
|
||||
useEffect(() => {
|
||||
async function fetchUsers() {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const token = localStorage.getItem('token') || document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('token='))
|
||||
?.split('=')[1];
|
||||
|
||||
// 외부 API 호출
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_BASE_URL
|
||||
? `${process.env.NEXT_PUBLIC_API_BASE_URL}/admin/users/compact`
|
||||
: 'https://hrdi.coconutmeet.net/admin/users/compact';
|
||||
|
||||
const response = await fetch(apiUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`사용자 데이터를 가져오는데 실패했습니다. (${response.status})`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// API 응답이 배열이 아닌 경우 처리 (예: { items: [...] } 형태)
|
||||
let usersArray: any[] = [];
|
||||
if (Array.isArray(data)) {
|
||||
usersArray = data;
|
||||
} else if (data && typeof data === 'object') {
|
||||
usersArray = data.items || data.users || data.data || data.list || [];
|
||||
}
|
||||
|
||||
// API 응답 데이터를 UserRow 형식으로 변환
|
||||
const transformedUsers: UserRow[] = usersArray.length > 0
|
||||
? usersArray.map((user: any) => {
|
||||
// 가입일을 YYYY-MM-DD 형식으로 변환
|
||||
const formatDate = (dateString: string | null | undefined): string => {
|
||||
if (!dateString) return new Date().toISOString().split('T')[0];
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return date.toISOString().split('T')[0];
|
||||
} catch {
|
||||
return new Date().toISOString().split('T')[0];
|
||||
}
|
||||
};
|
||||
|
||||
// null 값을 명시적으로 처리
|
||||
const getValue = (value: any, fallback: string = '-') => {
|
||||
if (value === null || value === undefined) return fallback;
|
||||
if (typeof value === 'string' && value.trim() === '') return fallback;
|
||||
return String(value);
|
||||
};
|
||||
|
||||
// status가 "ACTIVE"이면 활성화, 아니면 비활성화
|
||||
const accountStatus: AccountStatus =
|
||||
user.status === 'ACTIVE' || user.status === 'active' ? 'active' : 'inactive';
|
||||
|
||||
// role 데이터 처리 (API에서 role이 없을 수 있음)
|
||||
let userRole: RoleType = 'learner'; // 기본값
|
||||
if (user.role) {
|
||||
const roleLower = String(user.role).toLowerCase();
|
||||
if (roleLower === 'instructor' || roleLower === '강사') {
|
||||
userRole = 'instructor';
|
||||
} else if (roleLower === 'admin' || roleLower === '관리자') {
|
||||
userRole = 'admin';
|
||||
} else {
|
||||
userRole = 'learner';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: String(user.id || user.userId || Math.random()),
|
||||
joinDate: formatDate(user.createdAt || user.joinDate || user.join_date),
|
||||
name: getValue(user.name || user.userName, '-'),
|
||||
email: getValue(user.email || user.userEmail, '-'),
|
||||
role: userRole,
|
||||
status: accountStatus,
|
||||
};
|
||||
})
|
||||
: [];
|
||||
|
||||
setUsers(transformedUsers);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : '사용자 데이터를 불러오는 중 오류가 발생했습니다.';
|
||||
setError(errorMessage);
|
||||
console.error('사용자 데이터 로드 오류:', err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchUsers();
|
||||
}, []);
|
||||
|
||||
const filteredUsers = useMemo(() => {
|
||||
return activeTab === 'all'
|
||||
? users
|
||||
@@ -105,8 +208,63 @@ export default function AdminIdPage() {
|
||||
setIsDeactivateModalOpen(true);
|
||||
}
|
||||
|
||||
function handleDeactivateConfirm() {
|
||||
if (selectedUserId) {
|
||||
async function handleDeactivateConfirm() {
|
||||
if (!selectedUserId) {
|
||||
setIsDeactivateModalOpen(false);
|
||||
setSelectedUserId(null);
|
||||
setDeactivateReason('');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('token') || document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('token='))
|
||||
?.split('=')[1];
|
||||
|
||||
if (!token) {
|
||||
setToastMessage('로그인이 필요합니다.');
|
||||
setShowToast(true);
|
||||
setTimeout(() => {
|
||||
setShowToast(false);
|
||||
}, 3000);
|
||||
setIsDeactivateModalOpen(false);
|
||||
setSelectedUserId(null);
|
||||
setDeactivateReason('');
|
||||
return;
|
||||
}
|
||||
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_BASE_URL
|
||||
? `${process.env.NEXT_PUBLIC_API_BASE_URL}/admin/users/${selectedUserId}/unsuspend`
|
||||
: `https://hrdi.coconutmeet.net/admin/users/${selectedUserId}/unsuspend`;
|
||||
|
||||
const response = await fetch(apiUrl, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
reason: deactivateReason,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = `계정 비활성화 실패 (${response.status})`;
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
if (errorData.error) {
|
||||
errorMessage = errorData.error;
|
||||
} else if (errorData.message) {
|
||||
errorMessage = errorData.message;
|
||||
}
|
||||
} catch (parseError) {
|
||||
// ignore
|
||||
}
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// API 호출 성공 시 로컬 상태 업데이트
|
||||
setUsers(prevUsers =>
|
||||
prevUsers.map(user =>
|
||||
user.id === selectedUserId
|
||||
@@ -119,14 +277,25 @@ export default function AdminIdPage() {
|
||||
setTimeout(() => {
|
||||
setShowToast(false);
|
||||
}, 3000);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : '계정 비활성화 중 오류가 발생했습니다.';
|
||||
setToastMessage(errorMessage);
|
||||
setShowToast(true);
|
||||
setTimeout(() => {
|
||||
setShowToast(false);
|
||||
}, 3000);
|
||||
console.error('계정 비활성화 오류:', err);
|
||||
} finally {
|
||||
setIsDeactivateModalOpen(false);
|
||||
setSelectedUserId(null);
|
||||
setDeactivateReason('');
|
||||
}
|
||||
setIsDeactivateModalOpen(false);
|
||||
setSelectedUserId(null);
|
||||
}
|
||||
|
||||
function handleDeactivateCancel() {
|
||||
setIsDeactivateModalOpen(false);
|
||||
setSelectedUserId(null);
|
||||
setDeactivateReason('');
|
||||
}
|
||||
|
||||
function toggleAccountStatus(userId: string) {
|
||||
@@ -203,7 +372,19 @@ export default function AdminIdPage() {
|
||||
|
||||
{/* 콘텐츠 영역 */}
|
||||
<div className="flex-1 pt-8 flex flex-col">
|
||||
{filteredUsers.length === 0 ? (
|
||||
{isLoading ? (
|
||||
<div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center">
|
||||
<p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
|
||||
데이터를 불러오는 중...
|
||||
</p>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center">
|
||||
<p className="text-[16px] font-medium leading-[1.5] text-[#f64c4c]">
|
||||
{error}
|
||||
</p>
|
||||
</div>
|
||||
) : filteredUsers.length === 0 ? (
|
||||
<div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center">
|
||||
<p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
|
||||
현재 관리할 수 있는 회원 계정이 없습니다.
|
||||
@@ -215,19 +396,17 @@ export default function AdminIdPage() {
|
||||
<div className="w-full rounded-[8px] border border-[#dee1e6] overflow-visible">
|
||||
<table className="min-w-full border-collapse">
|
||||
<colgroup>
|
||||
<col style={{ width: 140 }} />
|
||||
<col style={{ width: 200 }} />
|
||||
<col />
|
||||
<col />
|
||||
<col style={{ width: 120 }} />
|
||||
<col style={{ width: 120 }} />
|
||||
<col style={{ width: 120 }} />
|
||||
<col style={{ width: 150 }} />
|
||||
<col style={{ width: 150 }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr className="h-12 bg-gray-50 text-left">
|
||||
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">가입일</th>
|
||||
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">성명</th>
|
||||
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">아이디(이메일)</th>
|
||||
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">권한설정</th>
|
||||
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">계정상태</th>
|
||||
<th className="px-4 text-center text-[14px] font-semibold leading-[1.5] text-[#4c5561]">계정관리</th>
|
||||
</tr>
|
||||
@@ -247,43 +426,6 @@ export default function AdminIdPage() {
|
||||
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
||||
{user.email}
|
||||
</td>
|
||||
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
||||
<div className="relative flex items-center justify-between">
|
||||
<span>{roleLabels[user.role]}</span>
|
||||
<div
|
||||
ref={(el) => { dropdownRefs.current[user.id] = el; }}
|
||||
className="relative"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleDropdown(user.id)}
|
||||
className="ml-2 flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity"
|
||||
>
|
||||
<DropdownIcon width={16} height={16} stroke="#8C95A1" />
|
||||
</button>
|
||||
{openDropdownId === user.id && (
|
||||
<div className="absolute right-0 top-full mt-1 z-[100] min-w-[120px] bg-white border border-[#dee1e6] rounded-[4px] shadow-lg flex flex-col">
|
||||
{(['learner', 'instructor', 'admin'] as RoleType[]).map((role) => (
|
||||
<button
|
||||
key={role}
|
||||
type="button"
|
||||
onClick={() => changeUserRole(user.id, role)}
|
||||
className={[
|
||||
"w-full px-4 py-2 text-left text-[14px] leading-[1.5] hover:bg-gray-50 transition-colors cursor-pointer",
|
||||
user.role === role
|
||||
? "text-[#1f2b91] font-semibold bg-[#ecf0ff]"
|
||||
: "text-[#1b2027]",
|
||||
role !== 'admin' && "border-b border-[#dee1e6]"
|
||||
].join(" ")}
|
||||
>
|
||||
{roleLabels[role]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
||||
{user.status === 'active' ? (
|
||||
<div className="inline-flex items-center justify-center h-[20px] px-[4px] rounded-[4px] bg-[#ecf0ff]">
|
||||
@@ -460,6 +602,15 @@ export default function AdminIdPage() {
|
||||
<br />
|
||||
계정을 비활성화 처리하시겠습니까?
|
||||
</p>
|
||||
<div className="w-full">
|
||||
<input
|
||||
type="text"
|
||||
value={deactivateReason}
|
||||
onChange={(e) => setDeactivateReason(e.target.value)}
|
||||
placeholder="비활성화 사유를 입력해주세요"
|
||||
className="w-full h-[40px] px-[12px] rounded-[8px] border border-[#dee1e6] text-[14px] leading-[1.5] text-[#1b2027] placeholder:text-[#9ca3af] focus:outline-none focus:ring-2 focus:ring-[#1f2b91] focus:border-transparent"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 items-center justify-end">
|
||||
<button
|
||||
|
||||
6
src/app/admin/page.tsx
Normal file
6
src/app/admin/page.tsx
Normal file
@@ -0,0 +1,6 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function AdminPage() {
|
||||
redirect('/admin/id');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user