-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadminService.ts
More file actions
326 lines (293 loc) · 8.85 KB
/
Copy pathadminService.ts
File metadata and controls
326 lines (293 loc) · 8.85 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
import router from '@/router'
import { api } from './api'
import type { ApiResponse } from './authService'
import type { PendingRecord } from './userService'
// Types for admin requests and responses
export interface User {
id: number
username: string
email: string
admin: boolean
verified: boolean
balance: number
created_at: string
updated_at: string
}
export interface Voucher {
id: number
voucher: string
value: number
used: boolean
used_by?: number
created_at: string
expires_at: string
}
export interface GenerateVouchersRequest {
count: number
value: number
expire_after_days: number
}
export interface GenerateVouchersResponse {
message: string
vouchers: Voucher[]
}
export interface CreditUserRequest {
amount: number
memo: string
}
export interface CreditUserResponse {
message: string
user: string
amount: number
memo: string
}
export interface DeleteUserResponse {
message: string
}
export interface SystemEmail {
title: string
message: string
priority: string
}
export interface SystemEmailResponse {
failed_emails: string[]
failed_emails_count: number
successful_emails: number
total_users: number
}
export interface AdminWorkflow {
uuid: string
name: string
display_name: string
status: string
current_step: number
total_steps: number
step_name: string
state: Record<string, any>
user_id: number
created_at: string
queue_name: string
metadata: Record<string, string>
error?: string
}
export interface Invoice {
id: number
user_id: number
total: number
nodes: any[]
tax: number
created_at: string
}
// Admin service class
export class AdminService {
private static instance: AdminService
private constructor() {}
static getInstance(): AdminService {
if (!AdminService.instance) {
AdminService.instance = new AdminService()
}
return AdminService.instance
}
// List all users (requires admin auth)
async listUsers(): Promise<User[]> {
const response = await api.get<ApiResponse<{ users: User[] }>>('/v1/users', {
requiresAuth: true,
showNotifications: true,
errorMessage: 'Failed to load users',
})
return response.data.data?.users || []
}
// Delete a user (requires admin auth)
async deleteUser(userId: number): Promise<DeleteUserResponse> {
const response = await api.delete<DeleteUserResponse>(`/v1/users/${userId}`, {
requiresAuth: true,
showNotifications: true,
loadingMessage: 'Deleting user...',
errorMessage: 'Failed to delete user',
})
return response.data
}
// Credit a user's balance (requires admin auth)
async creditUser(userId: number, data: CreditUserRequest): Promise<CreditUserResponse> {
const response = await api.post<CreditUserResponse>(`/v1/users/${userId}/credit`, data, {
requiresAuth: true,
showNotifications: true,
loadingMessage: 'Crediting user...',
errorMessage: 'Failed to credit user',
})
return response.data
}
// Drain a user's balance to system account (requires admin auth)
async drainUser(userId: number): Promise<void> {
await api.post<void>(
`/v1/users/${userId}/drain`,
{},
{
requiresAuth: true,
showNotifications: true,
loadingMessage: 'Draining user balance...',
errorMessage: 'Failed to drain user balance',
},
)
}
// Drain all users' balances to system account (requires admin auth)
async drainAllUsers(): Promise<void> {
await api.post<void>(
`/v1/users/drain-all`,
{},
{
requiresAuth: true,
showNotifications: true,
loadingMessage: "Draining all users' balances...",
errorMessage: "Failed to drain all users' balances",
},
)
}
// Generate vouchers (requires admin auth)
async generateVouchers(data: GenerateVouchersRequest): Promise<GenerateVouchersResponse> {
const response = await api.post<GenerateVouchersResponse>('/v1/vouchers/generate', data, {
requiresAuth: true,
showNotifications: true,
loadingMessage: 'Generating vouchers...',
errorMessage: 'Failed to generate vouchers',
})
return response.data
}
// List all vouchers (requires admin auth)
async listVouchers(): Promise<Voucher[]> {
const response = await api.get<ApiResponse<{ vouchers: Voucher[] }>>('/v1/vouchers', {
requiresAuth: true,
showNotifications: true,
errorMessage: 'Failed to load vouchers',
})
return response.data.data?.vouchers || []
}
// List all invoices (requires admin auth)
async listInvoices(): Promise<Invoice[]> {
const response = await api.get<ApiResponse<{ invoices: Invoice[] }>>('/v1/invoices', {
requiresAuth: true,
showNotifications: true,
errorMessage: 'Failed to load invoices',
})
return response.data.data?.invoices || []
}
// List all pending records (requires admin auth)
async listPendingRecords(): Promise<PendingRecord[]> {
const response = await api.get<ApiResponse<{ pending_records: PendingRecord[] }>>(
'/v1/pending-records',
{
requiresAuth: true,
showNotifications: true,
errorMessage: 'Failed to load payments',
},
)
return response.data.data?.pending_records || []
}
// Send a system email to all users (requires admin auth)
async sendSystemEmail(formData: FormData): Promise<SystemEmailResponse> {
const response = await api.post<SystemEmailResponse>('/v1/users/mail', formData, {
requiresAuth: true,
showNotifications: true,
loadingMessage: 'Sending email to all users',
errorMessage: 'Failed to send email',
contentType: '',
timeout: 60000,
})
return response.data
}
// List all workflows (requires admin auth)
async listWorkflows(status?: string): Promise<AdminWorkflow[]> {
const url = status ? `/v1/workflows?status=${status}` : '/v1/workflows'
const response = await api.get<ApiResponse<{ workflows: AdminWorkflow[] }>>(url, {
requiresAuth: true,
showNotifications: true,
errorMessage: 'Failed to load workflows',
})
return response.data.data?.workflows || []
}
// List workflows with pagination
async listWorkflowsPaginated(
status?: string,
page: number = 1,
limit: number = 10,
): Promise<{
workflows: AdminWorkflow[]
total: number
page: number
limit: number
total_pages: number
}> {
try {
const params = new URLSearchParams()
if (status) params.append('status', status)
params.append('page', page.toString())
params.append('limit', limit.toString())
const url = `/v1/workflows?${params.toString()}`
const response = await api.get<
ApiResponse<{
workflows: AdminWorkflow[]
total: number
page: number
limit: number
total_pages: number
}>
>(url, {
requiresAuth: true,
errorMessage: 'Failed to load workflows',
})
// Handle the response safely
if (!response || !response.data) {
console.warn('Empty response from workflows endpoint')
return { workflows: [], total: 0, page, limit, total_pages: 0 }
}
const data = response.data.data
if (!data) {
console.warn('No data in workflows response')
return { workflows: [], total: 0, page, limit, total_pages: 0 }
}
return {
workflows: data.workflows || [],
total: data.total || 0,
page: data.page || page,
limit: data.limit || limit,
total_pages: data.total_pages || 0,
}
} catch (error) {
console.error('Error fetching workflows:', error)
throw error
}
}
// Retry a failed workflow (admin)
async retryWorkflow(workflowUUID: string): Promise<void> {
await api.get<void>(`/v1/workflows/retry/${encodeURIComponent(workflowUUID)}`, {
requiresAuth: true,
showNotifications: true,
loadingMessage: 'Retrying workflow...',
successMessage: 'Workflow retry initiated',
errorMessage: 'Failed to retry workflow',
})
}
async SetMaintenanceModeStatus(status: boolean): Promise<void> {
try {
const response = await api.put(
'/v1/system/maintenance/status',
{ enabled: status },
{
requiresAuth: true,
showNotifications: true,
loadingMessage: status ? 'Enabling maintenance mode...' : 'Disabling maintenance mode...',
successMessage: status
? 'Maintenance mode enabled successfully'
: 'Maintenance mode disabled successfully',
errorMessage: 'Failed to set maintenance mode',
},
)
// Note: No redirect needed - router guard will handle redirecting non-admin users
// Admins can continue working on the admin dashboard
} catch (error) {
console.error(error)
throw error
}
}
}
export const adminService = AdminService.getInstance()