import {BaseService} from '../core/base.service'; import type { AdminUser, AuthSource, AuthSourceRequest, CreateSystemConfigRequest, CreateTemplateRequest, CreateUserRequest, DispatchTaskRequest, ListTaskExecutionsRequest, ListTaskExecutionsResponse, ListUsersRequest, ListUsersResponse, SystemConfig, SystemStatus, TaskExecution, TaskMeta, TaskTypeResponse, Template, ToggleAuthSourceRequest, UpdateSystemConfigRequest, UpdateTemplateRequest, UpdateUserStatusRequest, } from './types'; export type { AdminUser } from './types'; /** * 管理员服务 * 处理系统配置和用户积分配置管理相关的 API 请求 * * @remarks * 所有接口都需要管理员权限 */ export class AdminService extends BaseService { protected static readonly basePath = '/api/v1/admin'; // ==================== 系统配置管理 ==================== /** * 创建系统配置 * @param request - 创建系统配置的请求参数 * @returns void * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 * @throws {ValidationError} 当参数验证失败或配置键已存在时 * * @example * ```typescript * await AdminService.createSystemConfig({ * key: 'app.version', * value: '1.0.0', * description: '应用版本号' * }); * ``` */ static async createSystemConfig( request: CreateSystemConfigRequest, ): Promise { return this.post('/system-configs', request); } /** * 获取系统配置列表 * @returns 系统配置列表 * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 * * @example * ```typescript * const configs = await AdminService.listSystemConfigs(); * console.log('系统配置数量:', configs.length); * ``` */ static async listSystemConfigs(type?: 'system' | 'business'): Promise { const query = type ? `?type=${type}` : ''; return this.get(`/system-configs${query}`); } /** * 获取单个系统配置 * @param key - 配置键 * @returns 系统配置信息 * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 * @throws {NotFoundError} 当配置不存在时 * * @example * ```typescript * const config = await AdminService.getSystemConfig('app.version'); * console.log('应用版本:', config.value); * ``` */ static async getSystemConfig(key: string): Promise { return this.get(`/system-configs/${ key }`); } /** * 更新系统配置 * @param key - 配置键 * @param request - 更新系统配置的请求参数 * @returns void * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 * @throws {NotFoundError} 当配置不存在时 * @throws {ValidationError} 当参数验证失败时 * * @example * ```typescript * await AdminService.updateSystemConfig('app.version', { * value: '1.1.0', * description: '更新到新版本' * }); * ``` */ static async updateSystemConfig( key: string, request: UpdateSystemConfigRequest, ): Promise { return this.put(`/system-configs/${ key }`, request); } static async testSMTP(request: { smtp_host: string; smtp_port: number; smtp_username: string; smtp_password: string; to: string; }): Promise<{ success: boolean; log: string; error: string }> { return this.post<{ success: boolean; log: string; error: string }>('/system-configs/smtp/test', request); } // ==================== 认证源管理 ==================== static async listAuthSources(): Promise { return this.get('/auth-sources'); } static async createAuthSource(request: AuthSourceRequest): Promise { return this.post('/auth-sources', request); } static async updateAuthSource(id: string, request: AuthSourceRequest): Promise { return this.put(`/auth-sources/${ id }`, request); } static async toggleAuthSource(id: string, request: ToggleAuthSourceRequest): Promise { return this.put(`/auth-sources/${ id }/toggle`, request); } static async deleteAuthSource(id: string): Promise { return this.delete(`/auth-sources/${ id }`); } // ==================== 任务管理 ==================== /** * 获取支持的任务类型列表 * @returns 任务类型列表 * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 * * @example * ```typescript * const taskTypes = await AdminService.getTaskTypes(); * console.log('可用任务类型:', taskTypes); * ``` */ static async getTaskTypes(): Promise { const response = await this.get('/tasks/types'); // Adapt backend PascalCase to frontend snake_case return response.map(item => ({ type: item.Type || item.type || '', asynq_task: item.AsynqTask || item.asynq_task || '', name: item.Name || item.name || '', description: item.Description || item.description || '', supports_time: item.SupportsTime ?? item.supports_time ?? false, max_retry: item.MaxRetry ?? item.max_retry ?? 0, queue: item.Queue || item.queue || '', params: (item.Params || item.params || []).map(p => ({ name: p.Name || p.name || '', label: p.Label || p.label || '', type: p.Type || p.type || '', required: p.Required ?? p.required ?? false, placeholder: p.Placeholder || p.placeholder || '', description: p.Description || p.description || '', })), })); } /** * 下发任务 * @param request - 下发任务请求参数 * @returns void * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 * @throws {ValidationError} 当参数验证失败时 * * @example * ```typescript * // 下发订单同步任务(带时间范围) * await AdminService.dispatchTask({ * task_type: 'order_sync', * start_time: '2025-12-01T00:00:00Z', * end_time: '2025-12-27T23:59:59Z' * }); * * // 下发用户积分更新任务 * await AdminService.dispatchTask({ * task_type: 'user_gamification', * user_id: 123 * }); * * // 下发争议自动退款任务 * await AdminService.dispatchTask({ * task_type: 'dispute_auto_refund' * }); * ``` * * @remarks * - 不同任务类型需要不同的参数 * - order_sync 支持 start_time 和 end_time 参数 * - user_gamification 需要 user_id 参数 * - 其他任务无需额外参数 */ static async dispatchTask(request: DispatchTaskRequest): Promise { return this.post('/tasks/dispatch', request); } /** * 查询任务执行记录列表 */ static async listTaskExecutions( request: ListTaskExecutionsRequest = {}, ): Promise { return this.get( '/tasks/executions', request as unknown as Record, ); } /** * 查询任务执行详情 */ static async getTaskExecution(id: string): Promise { return this.get(`/tasks/executions/${ id }`); } /** * 重试失败任务 */ static async retryTaskExecution(id: string): Promise { return this.post(`/tasks/executions/${ id }/retry`); } // ==================== 用户管理 ==================== /** * 获取用户列表 * @param request - 查询参数 * @returns 用户列表及总数 * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 * @throws {ValidationError} 当参数验证失败时 * * @example * ```typescript * const result = await AdminService.listUsers({ * page: 1, * page_size: 20, * user_id: '10001', * username: 'test' * }); * console.log('用户总数:', result.total); * console.log('用户列表:', result.users); * ``` * * @remarks * - page 从 1 开始 * - page_size 范围 1-100 * - user_id 按用户 ID 精确搜索 * - username 按用户名做前缀搜索 */ static async listUsers(request: ListUsersRequest): Promise { return this.get('/users', request as unknown as Record); } /** * 更新用户状态 * @param id - 用户 ID * @param request - 更新状态请求参数 * @returns void * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限或禁用管理员用户时 * @throws {NotFoundError} 当用户不存在时 * * @example * ```typescript * // 禁用用户 * await AdminService.updateUserStatus(123, { is_active: false }); * * // 启用用户 * await AdminService.updateUserStatus(123, { is_active: true }); * ``` * * @remarks * - 不能禁用管理员用户 */ static async updateUserStatus( id: string, request: UpdateUserStatusRequest ): Promise { return this.put(`/users/${ id }/status`, request); } /** * 创建用户 * @param request - 创建用户请求参数 * @returns 创建成功的用户信息 */ static async createUser(request: CreateUserRequest): Promise { return this.post('/users', request); } /** * 获取系统状态 * @returns 系统状态指标数据 * @throws {UnauthorizedError} 当未登录时 * @throws {ForbiddenError} 当无管理员权限时 */ static async getSystemStatus(): Promise { return this.get('/status'); } // ==================== 系统日志 ==================== /** * 获取系统历史日志 * @param cursor - 日志游标,0=获取最新,>0=获取更早 * @param limit - 每页条数,默认 200 */ static async getLogs(cursor: number = 0, limit: number = 200): Promise<{ lines: Array<{ index: number; data: string }>; has_more: boolean; next_cursor: number; }> { return this.get('/logs', { cursor, limit }); } // ==================== 模板管理 ==================== /** * 获取模板列表 */ static async listTemplates(): Promise { return this.get('/templates'); } /** * 获取单个模板 */ static async getTemplate(key: string): Promise