File size: 9,762 Bytes
eb6a2f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// ─────────────────────────────────────────────────────────────────────────────
// src/lib/api/adminUserManagementApi.ts
// User Management API for Admin Dashboard
// Based on the official API documentation - completely independent from adminApi
// ─────────────────────────────────────────────────────────────────────────────

import { getApiBaseUrl } from './config';

const BASE_URL = getApiBaseUrl();
const TOKEN_KEY = 'authToken';

// ─── Custom Error Class ───────────────────────────────────────────────────────

export class UserManagementApiError extends Error {
  readonly status: number;
  readonly path: string;

  constructor(
    status: number,
    message: string,
    path: string,
  ) {
    super(`[${status}] ${path} β†’ ${message}`);
    this.status = status;
    this.path = path;
    this.name = 'UserManagementApiError';
  }
}

// ─── Shared helper ────────────────────────────────────────────────────────────

function getHeaders(): HeadersInit {
  const token = localStorage.getItem(TOKEN_KEY) ?? '';
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

async function request<T>(path: string, options?: RequestInit): Promise<T> {
  const url = `${BASE_URL}${path}`;

  // Guard: expired token
  const token = localStorage.getItem(TOKEN_KEY);
  if (token) {
    try {
      const payload = JSON.parse(atob(token.split('.')[1]));
      if (payload?.exp && payload.exp * 1000 < Date.now()) {
        localStorage.removeItem(TOKEN_KEY);
        throw new UserManagementApiError(401, 'Session expired β€” please log in again', path);
      }
    } catch (e) {
      if (e instanceof UserManagementApiError) throw e;
      localStorage.removeItem(TOKEN_KEY);
    }
  }

  try {
    const res = await fetch(url, {
      ...options,
      headers: { ...getHeaders(), ...options?.headers },
    });

    // Handle 204 No Content
    if (res.status === 204) {
      return null as T;
    }

    if (!res.ok) {
      const message = await res.text().catch(() => res.statusText);
      throw new UserManagementApiError(res.status, message, path);
    }

    const text = await res.text();
    if (!text.trim()) {
      return null as T;
    }

    try {
      return JSON.parse(text) as T;
    } catch {
      return text as unknown as T;
    }
  } catch (error) {
    if (error instanceof UserManagementApiError) throw error;
    throw new Error(`Network error while calling ${path}`);
  }
}

// ─── Response Types ───────────────────────────────────────────────────────────

export interface UserManagementStatsDto {
  totalUsers: number;
  totalSheikhs: number;
  totalStudents: number;
  blockedUsers: number;
}

export interface StudentDtoAdmin {
  id: number;
  name: string;
  email: string;
  registrationDate: string;
  streak: number;
  totalSessions: number;
  status: 'ACTIVE' | 'BLOCKED' | 'INACTIVE';
}

export interface SheikhDtoAdmin {
  id: number;
  name: string;
  email: string;
  registrationDate: string;
  numberOfSessions: number;
  totalRevenue: number;
  averageRating: number;
  status: 'ACTIVE' | 'BLOCKED' | 'PENDING' | 'APPROVED' | 'REJECTED';
}

export type UserDtoAdmin = StudentDtoAdmin | SheikhDtoAdmin;

export interface DetailedStudentView {
  id: number;
  name: string;
  email: string;
  registrationDate: string;
  streak: number;
  sessionCount: number;
  country: string;
  numberOfCompletedSessions: number;
  totalSpentTime: number;
}

export interface DetailedSheikhView {
  id: number;
  name: string;
  email: string;
  country: string;
  experienceYears: number;
  bio: string;
  specialization: string;
  hourlyRate: number;
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'ACTIVE' | 'BLOCKED';
  registrationDate: string;
  averageRating: number;
  numberOfCompletedSessions: number;
  numberOfStudents: number;
  numberofReviews: number;
  sessionCount: number;
  totalEarnings: number;
}

export interface SessionHistoryDto {
  sessionId: number;
  sheikhName: string;
  studentName: string;
  date: string;
  status: 'COMPLETED' | 'CANCELLED' | 'PENDING' | 'SCHEDULED';
  price: number;
  durationInMinutes: number;
  rate: number;
}

export interface SheikhProfileResponse {
  sheikhProfile: DetailedSheikhView;
  sessionHistories: SessionHistoryDto[];
}

export interface StudentProfileResponse {
  studentProfile: DetailedStudentView;
  sessionHistories: SessionHistoryDto[];
}

// ─── API Functions ────────────────────────────────────────────────────────────

/**
 * GET /api/admin/user-management/stats
 * Retrieves comprehensive statistics about all users in the platform.
 */
export async function fetchUserManagementStats(): Promise<UserManagementStatsDto> {
  return request<UserManagementStatsDto>('/api/admin/user-management/stats');
}

/**
 * GET /api/admin/user-management/students
 * Retrieves a list of all students with basic information.
 */
export async function fetchAllStudents(): Promise<StudentDtoAdmin[]> {
  return request<StudentDtoAdmin[]>('/api/admin/user-management/students');
}

/**
 * GET /api/admin/user-management/sheikhs
 * Retrieves a list of all sheikhs with basic information.
 */
export async function fetchAllSheikhs(): Promise<SheikhDtoAdmin[]> {
  return request<SheikhDtoAdmin[]>('/api/admin/user-management/sheikhs');
}

/**
 * GET /api/admin/user-management/users
 * Retrieves a combined list of all users (students and sheikhs).
 */
export async function fetchAllUsers(): Promise<UserDtoAdmin[]> {
  return request<UserDtoAdmin[]>('/api/admin/user-management/users');
}

/**
 * POST /api/admin/user-management/block-user
 * Blocks a user account, preventing them from accessing the platform.
 * @param userId - ID of the user to block
 */
export async function blockUser(userId: number): Promise<void> {
  return request<void>(`/api/admin/user-management/block-user?userId=${userId}`, {
    method: 'POST',
  });
}

/**
 * POST /api/admin/user-management/unblock-user
 * Unblocks a previously blocked user account.
 * @param userId - ID of the user to unblock
 */
export async function unblockUser(userId: number): Promise<void> {
  return request<void>(`/api/admin/user-management/unblock-user?userId=${userId}`, {
    method: 'POST',
  });
}

/**
 * GET /api/admin/user-management/sheikh-profile
 * Retrieves detailed profile information for a specific sheikh including session history.
 * @param userId - Sheikh's ID
 */
export async function fetchSheikhProfile(userId: number): Promise<SheikhProfileResponse> {
  return request<SheikhProfileResponse>(`/api/admin/user-management/sheikh-profile?userId=${userId}`);
}

/**
 * GET /api/admin/user-management/student-profile
 * Retrieves detailed profile information for a specific student including session history.
 * @param userId - Student's ID
 */
export async function fetchStudentProfile(userId: number): Promise<StudentProfileResponse> {
  return request<StudentProfileResponse>(`/api/admin/user-management/student-profile?userId=${userId}`);
}

// ─── Convenience: load all user management data ───────────────────────────────

export interface UserManagementData {
  stats: UserManagementStatsDto;
  students: StudentDtoAdmin[];
  sheikhs: SheikhDtoAdmin[];
  users: UserDtoAdmin[];
}

export async function fetchUserManagementData(): Promise<{
  data: Partial<UserManagementData>;
  errors: Record<string, string>;
}> {
  const [statsResult, studentsResult, sheikhsResult, usersResult] = await Promise.allSettled([
    fetchUserManagementStats(),
    fetchAllStudents(),
    fetchAllSheikhs(),
    fetchAllUsers(),
  ]);

  const data: Partial<UserManagementData> = {};
  const errors: Record<string, string> = {};

  if (statsResult.status === 'fulfilled') {
    data.stats = statsResult.value;
  } else {
    errors.stats = statsResult.reason?.message ?? 'Failed to load statistics';
  }

  if (studentsResult.status === 'fulfilled') {
    data.students = studentsResult.value;
  } else {
    errors.students = studentsResult.reason?.message ?? 'Failed to load students';
  }

  if (sheikhsResult.status === 'fulfilled') {
    data.sheikhs = sheikhsResult.value;
  } else {
    errors.sheikhs = sheikhsResult.reason?.message ?? 'Failed to load sheikhs';
  }

  if (usersResult.status === 'fulfilled') {
    data.users = usersResult.value;
  } else {
    errors.users = usersResult.reason?.message ?? 'Failed to load users';
  }

  return { data, errors };
}

// ─── Default export ───────────────────────────────────────────────────────────

const adminUserManagementApi = {
  fetchUserManagementStats,
  fetchAllStudents,
  fetchAllSheikhs,
  fetchAllUsers,
  blockUser,
  unblockUser,
  fetchSheikhProfile,
  fetchStudentProfile,
  fetchUserManagementData,
  UserManagementApiError,
};

export default adminUserManagementApi;