UNPKG

@warriorteam/redai-api-sdk

Version:
1,509 lines (1,495 loc) 44.5 kB
import { AxiosRequestConfig } from 'axios'; /** * Configuration for SDK HTTP Client */ interface HttpClientConfig { /** Base URL of the API */ baseUrl: string; /** Default timeout in milliseconds */ timeout?: number; /** Default headers */ headers?: Record<string, string>; } /** * API Response wrapper */ interface ApiResponse<T = unknown> { code: number; message: string; result: T; } /** * Paginated result wrapper */ interface PaginatedResult<T> { items: T[]; total: number; page: number; limit: number; totalPages: number; } /** * HTTP Client for SDK */ declare class HttpClient { private client; private authToken; constructor(config: HttpClientConfig); /** * Set authentication token */ setAuthToken(token: string): void; /** * Clear authentication token */ clearAuthToken(): void; /** * Get current auth token */ getAuthToken(): string | null; /** * GET request */ get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; /** * POST request */ post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; /** * PUT request */ put<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; /** * PATCH request */ patch<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; /** * DELETE request */ delete<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>; } /** * Common types used across dashboard-generic module */ /** * Multi-language label interface */ interface I18nLabel { vi?: string; en?: string; zh?: string; [key: string]: string | undefined; } /** * Sort direction enum */ declare enum SortDirection { ASC = "ASC", DESC = "DESC" } /** * Base query parameters for pagination */ interface QueryParams { /** Current page number (starts from 1) */ page?: number; /** Number of records per page */ limit?: number; /** Search keyword */ search?: string; /** Fields to search in (comma-separated) */ searchBy?: string; /** Field to sort by */ sortBy?: string; /** Sort direction */ sortDirection?: SortDirection; } /** * HTTP Method types */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; /** * API Status types */ type ApiStatus = 'active' | 'inactive' | 'deprecated'; /** * Page Template Status types */ type PageTemplateStatus = 'draft' | 'active' | 'archived'; /** * Page Template Type enum */ declare enum PageTemplateType { TEMPLATE = "TEMPLATE", USER = "USER", ADMIN = "ADMIN" } /** * Dashboard Module enum */ declare enum DashboardModule { BUSINESS = "BUSINESS", MARKETING = "MARKETING", AGENT = "AGENT", RPOINT = "RPOINT", DATA = "DATA", USER_TOOL_CUSTOM = "USER_TOOL_CUSTOM" } /** * Dashboard Chart Type enum */ declare enum DashboardChartType { PIECHART = "PIECHART", LINECHART = "LINECHART", OVERVIEW = "OVERVIEW", AREACHART = "AREACHART", FUNNELCHART = "FUNNELCHART", HEATMAP = "HEATMAP", TABLECHART = "TABLECHART", TIMELINECHART = "TIMELINECHART", COHORTCHART = "COHORTCHART" } /** * Layout types for page templates */ type LayoutType = 'default' | 'sidebar' | 'full-width' | 'grid'; /** * Auth config type */ type AuthType = 'bearer' | 'api-key' | 'basic' | 'none'; /** * Resource type */ type ResourceType = 'api' | 'custom_tool'; /** * Resource prefix constants */ declare const RESOURCE_PREFIX: { readonly PAGE_TEMPLATE_API: "pta"; readonly API: "api"; readonly CUSTOM_TOOL: "tool"; }; type ResourcePrefix = typeof RESOURCE_PREFIX[keyof typeof RESOURCE_PREFIX]; /** * Schema interface for API input/output */ interface Schema { type: string; properties?: Record<string, Schema>; items?: Schema; required?: string[]; format?: string; description?: string; enum?: string[]; default?: unknown; [key: string]: unknown; } /** * Rate limit configuration */ interface RateLimitConfig { requestsPerMinute?: number; requestsPerHour?: number; burstLimit?: number; } /** * Auth configuration */ interface AuthConfig { type: 'bearer' | 'api-key' | 'basic' | 'none'; required: boolean; headerName?: string; keyPrefix?: string; } /** * Cache configuration */ interface CacheConfig { enabled: boolean; ttl?: number; keyPrefix?: string; } /** * Retry configuration */ interface RetryConfig { maxAttempts: number; backoffMs: number; retryableStatusCodes: number[]; } /** * Request: Create API configuration */ interface CreateApiRequest { /** Display name (multi-language) */ name: I18nLabel; /** Unique identifier code */ code: string; /** Description (multi-language) */ description?: I18nLabel; /** Input data structure */ inputSchema?: Schema; /** Output data structure */ outputSchema?: Schema; /** HTTP method */ method?: HttpMethod; /** API endpoint URL */ endpoint?: string; /** Request timeout in milliseconds */ timeoutMs?: number; /** Rate limiting configuration */ rateLimit?: RateLimitConfig; /** Authentication requirements */ authConfig?: AuthConfig; /** Custom headers */ customHeaders?: Record<string, string>; /** Cache configuration */ cacheConfig?: CacheConfig; /** Retry configuration */ retryConfig?: RetryConfig; /** Tags for categorization */ tags?: string[]; /** API status */ status?: ApiStatus; /** Version of the API */ version?: string; } /** * Request: Update API configuration (all fields optional) */ type UpdateApiRequest = Partial<CreateApiRequest>; /** * Request: Query API configurations */ interface QueryApiRequest extends QueryParams { /** Filter by HTTP method */ method?: HttpMethod; /** Filter by API status */ status?: ApiStatus; /** Filter by tags */ tags?: string[]; /** Filter by authentication requirement */ requiresAuth?: boolean; /** Filter by cache enabled */ cacheEnabled?: boolean; /** Filter by version */ version?: string; /** Filter by creator user ID */ createdBy?: number; /** Filter by category */ category?: string; /** Filter by dashboard module */ module?: DashboardModule; } /** * Response: API configuration */ interface ApiConfigResponse { /** API ID */ id: string; /** Display name (multi-language) */ name: I18nLabel; /** Unique identifier code */ code: string; /** Description (multi-language) */ description?: I18nLabel; /** Dashboard module */ module?: DashboardModule; /** Input data structure */ inputSchema?: Schema; /** Output data structure */ outputSchema?: Schema; /** HTTP method */ method: HttpMethod; /** API endpoint URL */ endpoint?: string; /** Request timeout in milliseconds */ timeoutMs: number; /** Rate limiting configuration */ rateLimit?: RateLimitConfig; /** Authentication requirements */ authConfig?: AuthConfig; /** Custom headers */ customHeaders?: Record<string, string>; /** Cache configuration */ cacheConfig?: CacheConfig; /** Retry configuration */ retryConfig?: RetryConfig; /** Tags for categorization */ tags?: string[]; /** API status */ status: ApiStatus; /** Version of the API */ version?: string; /** Owner user ID */ createdBy?: number; /** Last updated by user ID */ updatedBy?: number; /** Creation timestamp */ createdAt: number; /** Last update timestamp */ updatedAt?: number; /** Whether API is active */ isActive: boolean; /** Full API reference */ apiReference: string; /** Whether API has valid input schema */ hasValidInputSchema: boolean; /** Whether API has valid output schema */ hasValidOutputSchema: boolean; /** Whether API requires authentication */ requiresAuth: boolean; /** Cache TTL in seconds */ cacheTtl: number; /** Number of page templates using this API */ templateUsageCount?: number; } /** * Response: Dashboard module item */ interface DashboardModuleItem { value: string; label: I18nLabel; } /** * Response: API statistics */ interface ApiStatisticsResponse { totalApis: number; activeApis: number; inactiveApis: number; deprecatedApis: number; apisByMethod: Record<string, number>; recentApis: ApiConfigResponse[]; } /** * Layout configuration */ interface LayoutConfig { layout?: LayoutType; sidebarWidth?: number; headerHeight?: number; footerHeight?: number; theme?: string; customCSS?: string; } /** * SEO metadata */ interface SeoMeta { title?: string; description?: string; keywords?: string[]; ogImage?: string; } /** * Page configuration */ interface PageConfig { requireAuth?: boolean; allowedRoles?: string[]; cacheEnabled?: boolean; cacheTtl?: number; customHeaders?: Record<string, string>; } /** * Dependencies configuration */ interface Dependencies { libraries?: string[]; components?: string[]; stylesheets?: string[]; } /** * Usage statistics */ interface UsageStats { viewCount?: number; lastAccessed?: number; avgLoadTime?: number; } /** * Preview data */ interface PreviewData { thumbnailUrl?: string; screenshotUrl?: string; demoData?: Record<string, unknown>; } /** * Custom tool reference */ interface CustomToolRef { id: string; name: string; description?: string; } /** * Request: Create page template */ interface CreatePageTemplateRequest { /** Display name of the page */ name: string; /** Page description */ description?: string; /** React code text */ code: string; /** Page tags for filtering and search */ tags?: string[]; /** Associated API IDs */ apiIds?: string[]; /** Associated Custom Tool IDs */ userCustomToolIds?: string[]; /** Mapping of API ID to semantic code name */ apiCodeNames?: Record<string, string>; /** Mapping of Custom Tool ID to semantic code name */ customToolCodeNames?: Record<string, string>; } /** * Request: Update page template (all fields optional) */ type UpdatePageTemplateRequest = Partial<CreatePageTemplateRequest>; /** * Request: Query page templates */ interface QueryPageTemplateRequest extends QueryParams { /** Filter by publication status */ isPublished?: boolean; /** Filter by template status */ status?: PageTemplateStatus; /** Filter by category */ category?: string; /** Filter by tags */ tags?: string[]; /** Filter by featured flag */ isFeatured?: boolean; /** Filter by authentication requirement */ requiresAuth?: boolean; /** Filter by cache enabled */ cacheEnabled?: boolean; /** Filter by version */ version?: string; /** Filter by layout type */ layout?: LayoutType; /** Filter by creator user ID */ createdBy?: number; /** Filter by API association */ hasApiId?: string; /** Filter by theme */ theme?: string; /** Filter by template type */ type?: PageTemplateType; } /** * Request: Rename page template */ interface RenamePageTemplateRequest { name: string; } /** * Request: Associate APIs with page template */ interface AssociateApisRequest { apiIds: string[]; } /** * Request: Create from template customization */ interface CreateFromTemplateRequest { name?: string; description?: string; } /** * Template data for creation */ interface TemplateData { name: string; description?: string; code: string; } /** * Request: Create page template with template data */ interface CreateTemplateWithDataRequest { templateData?: TemplateData; apiIds?: string[]; userCustomToolIds?: string[]; apiCodeNames?: Record<string, string>; customToolCodeNames?: Record<string, string>; } /** * Response: Page template */ interface PageTemplateResponse { /** Page template ID */ id: string; /** Display name of the page */ name: string; /** Page description */ description?: string; /** React code text (only returned in detail API) */ code?: string; /** Publication status */ isPublished: boolean; /** Page category */ category?: string; /** Page tags */ tags?: string[]; /** Page layout configuration */ layoutConfig?: LayoutConfig; /** SEO metadata */ seoMeta?: SeoMeta; /** Page configuration */ pageConfig?: PageConfig; /** Component dependencies */ dependencies?: Dependencies; /** Template version */ version: string; /** Template status */ status: PageTemplateStatus; /** Featured flag */ isFeatured: boolean; /** Template type */ type: PageTemplateType; /** Sort order */ sortOrder: number; /** Usage statistics */ usageStats?: UsageStats; /** Template preview data */ previewData?: PreviewData; /** Owner user ID */ createdBy?: number; /** Creation timestamp */ createdAt: number; /** Last update timestamp */ updatedAt?: number; /** Associated APIs */ apis?: ApiConfigResponse[]; /** Associated Custom Tools */ customTools?: CustomToolRef[]; /** Whether template is ready for use */ isReady: boolean; /** Page URL */ pageUrl: string; /** Count of associated APIs */ apiCount: number; /** Whether template requires authentication */ requiresAuth: boolean; /** Allowed roles */ allowedRoles?: string[]; /** Dependency list */ dependenciesList?: Dependencies; } /** * Chart filter configuration */ interface ChartFilter { /** Field name */ field: string; /** Value */ value: unknown; /** Operator */ operator?: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'like'; } /** * Chart group by configuration */ interface ChartGroupBy { /** Field name to group by */ field: string; /** Multi-language labels for values */ labels?: Record<string, I18nLabel>; /** Colors for values */ colors?: Record<string, string>; /** Default value if null */ defaultValue?: string; } /** * Chart aggregate configuration */ interface ChartAggregate { /** Field name */ field: string; /** Aggregation type */ type: 'count' | 'sum' | 'avg' | 'min' | 'max'; } /** * Chart column configuration for Table Chart */ interface ChartColumn { /** Field name in entity */ field: string; /** Display key */ key: string; /** Multi-language label */ label: I18nLabel; /** Data type */ type: 'text' | 'number' | 'date' | 'boolean'; /** Whether sortable */ sortable?: boolean; /** Whether filterable */ filterable?: boolean; } /** * Funnel step configuration */ interface ChartFunnelStep { /** Step ID */ id: string; /** Multi-language label */ label: I18nLabel; /** Filter for this step */ filter?: ChartFilter; /** Color */ color?: string; } /** * Metric configuration for Dashboard Overview */ interface ChartMetric { /** Metric ID */ id: string; /** Multi-language label */ label: I18nLabel; /** Unit */ unit?: string; /** Filter for this metric */ filter?: ChartFilter; /** Aggregate config */ aggregate?: ChartAggregate; } /** * Metric group configuration */ interface ChartMetricGroup { /** Group ID */ id: string; /** Multi-language label */ label: I18nLabel; /** List of metrics */ metrics: ChartMetric[]; } /** * Generic chart configuration */ interface GenericChartConfig { /** Chart type */ chartType: DashboardChartType; /** Entity/table name to query */ entityName: string; /** Timestamp field name */ timestampField?: string; /** Group by configuration */ groupBy?: ChartGroupBy; /** Aggregate configuration */ aggregate?: ChartAggregate; /** Period: day, week, month */ period?: 'day' | 'week' | 'month'; /** Column configurations for Table Chart */ columns?: ChartColumn[]; /** Funnel steps for Funnel Chart */ funnelSteps?: ChartFunnelStep[]; /** X field for Heatmap */ xField?: string; /** Y field for Heatmap */ yField?: string; /** Title field for Timeline */ titleField?: string; /** Description field for Timeline */ descriptionField?: string; /** Type field for Timeline */ typeField?: string; /** Status field for Timeline */ statusField?: string; /** Metric groups for Overview */ metricGroups?: ChartMetricGroup[]; /** Additional filters */ filters?: ChartFilter[]; /** Page size */ pageSize?: number; /** Current page */ page?: number; /** Sort field */ sortField?: string; /** Sort order */ sortOrder?: 'ASC' | 'DESC'; /** Chart label */ chartLabel?: I18nLabel; /** Primary color */ color?: string; } /** * Execute API item request */ interface ExecuteApiItem { /** Dashboard module */ module: DashboardModule; /** API code identifier */ code: string; /** Type */ type: string; /** Start timestamp */ begin: number; /** End timestamp */ end: number; /** Generic chart configuration */ chartConfig?: GenericChartConfig; } /** * Request: Execute dashboard APIs */ interface ExecuteApiRequest { /** List of APIs to execute */ apis: ExecuteApiItem[]; } /** * Execute API result item */ interface ExecuteApiResultItem { /** Dashboard module */ module: DashboardModule; /** API code */ code: string; /** Chart type */ type: DashboardChartType; /** Response data */ data: unknown; /** Execution status */ status: 'success' | 'error'; /** Error message if any */ error?: string; } /** * Response: Execute API */ interface ExecuteApiResponse { /** List of execution results */ results: ExecuteApiResultItem[]; } /** * Resource execution item for batch execution */ interface ResourceExecutionItem { /** * Unified Resource ID with prefix * Format: "prefix:uuid" * - pta:uuid - PageTemplateApiEntity * - api:uuid - API Entity * - tool:uuid - Custom Tool */ resourceId: string; /** Integration ID (for custom tools only) */ integrationId?: string; /** Input parameters */ parameters?: Record<string, unknown>; } /** * Request: Execute resource (single or batch) */ interface ExecuteResourceRequest { /** * Unified Resource ID with prefix (NEW - Recommended) * Format: "prefix:uuid" (e.g., "api:550e8400-e29b-41d4-a716-446655440000") */ resourceId?: string; /** * @deprecated Use resourceId with "pta:" prefix instead */ pageTemplateApiId?: string; /** * @deprecated Use resourceId with "api:" prefix instead */ apiId?: string; /** * @deprecated Use resourceId with "tool:" prefix instead */ customToolId?: string; /** Integration ID (for custom tools only) */ integrationId?: string; /** Input parameters (single execution) */ parameters?: Record<string, unknown>; /** List of resources to execute in batch */ resources?: ResourceExecutionItem[]; } /** * Resource execution result */ interface ResourceExecutionResult { /** Resource ID that was executed */ resourceId: string; /** HTTP status code from API response */ statusCode: number; /** Response data from API */ data?: unknown; /** Response headers from API */ headers?: Record<string, string | string[]>; /** cURL command that was executed (debugging purpose) */ curlCommand?: string; /** Type of resource executed */ resourceType?: ResourceType; /** Error message when execution fails */ error?: string; } /** * Response: Execute resource * Returns array of ResourceExecutionResult */ type ExecuteResourceResponse = ResourceExecutionResult[]; /** * Code generation pattern */ type GenerationPattern = 'self-contained' | 'props-driven' | 'all-in-one'; /** * Request: Generate page from AI */ interface GeneratePageFromAiRequest { /** * Option 1: Provide pageTemplateId to auto-load all APIs and Custom Tools from that template */ pageTemplateId?: string; /** * Option 2: Manually specify API IDs */ apiIds?: string[]; /** * Option 3: Manually specify Custom Tool IDs */ userCustomToolIds?: string[]; /** AI prompt describing the desired dashboard layout and features */ prompt: string; /** Whether to save the generated template to database */ isSave?: 'TRUE' | 'FALSE'; /** Agent ID to use for AI generation */ agentId?: string; /** * Pattern for code generation: * - self-contained: Component tự fetch data với useExecuteResource (default) * - props-driven: Component nhận data từ props * - all-in-one: Component tự fetch data với pageTemplateApiId */ pattern?: GenerationPattern; /** Name for the generated page template */ name?: string; /** Description for the generated page template */ description?: string; } /** * Validation error item */ interface ValidationError { type: string; message: string; line?: number; code?: string; severity: 'error' | 'critical'; } /** * Saved template info */ interface SavedTemplateInfo { id: string; name: string; description?: string; code: string; apiIds: string[]; userCustomToolIds?: string[]; createdAt: number; } /** * Response: Generate page from AI */ interface GeneratePageFromAiResponse { /** Session ID for tracking the AI generation process */ sessionId: string; /** Whether the AI generation was successful */ success: boolean; /** Processing time in milliseconds */ processingTimeMs: number; /** Generated React code for the dashboard page */ generatedCode?: string; /** Saved page template if isSave was TRUE */ savedTemplate?: SavedTemplateInfo; /** Error message if generation failed */ error?: string; /** Validation errors if code validation failed */ validationErrors?: ValidationError[]; /** Quality review issues from AI */ qualityReview?: string[]; } /** * Response: Generate HTML page from AI */ interface GeneratePageHtmlFromAiResponse { /** Session ID for tracking the AI generation process */ sessionId: string; /** Whether the AI generation was successful */ success: boolean; /** Processing time in milliseconds */ processingTimeMs: number; /** Generated HTML markup */ generatedHtml?: string; /** Error message if generation failed */ error?: string; /** Validation errors if the generated HTML did not pass basic checks */ validationErrors?: string[]; /** Quality review issues from AI */ qualityReview?: string[]; } /** * Service for managing API configurations * Maps to: ApiController (api.controller.ts) * Base path: /dashboard-generic/apis */ declare class ApiService { private readonly httpClient; private readonly basePath; constructor(httpClient: HttpClient); /** * Get all API configurations with pagination and filtering * * @param query - Query parameters for filtering and pagination * @returns Paginated list of API configurations * * @example * ```typescript * const result = await apiService.findAll({ * page: 1, * limit: 10, * method: 'GET', * status: 'active', * }); * ``` */ findAll(query?: QueryApiRequest): Promise<ApiResponse<PaginatedResult<ApiConfigResponse>>>; /** * Get API configuration by ID * * @param id - API configuration ID (UUID) * @returns API configuration details * * @example * ```typescript * const api = await apiService.findOne('123e4567-e89b-12d3-a456-426614174000'); * ``` */ findOne(id: string): Promise<ApiResponse<ApiConfigResponse>>; /** * Get API configuration by code * * @param code - API configuration code * @returns API configuration details * * @example * ```typescript * const api = await apiService.findByCode('getUser'); * ``` */ findByCode(code: string): Promise<ApiResponse<ApiConfigResponse>>; /** * Update API configuration * * @param id - API configuration ID (UUID) * @param data - Update data * @returns Updated API configuration * * @example * ```typescript * const updated = await apiService.update('123e4567-e89b-12d3-a456-426614174000', { * status: 'inactive', * timeoutMs: 60000, * }); * ``` */ update(id: string, data: UpdateApiRequest): Promise<ApiResponse<ApiConfigResponse>>; /** * Delete API configuration * * @param id - API configuration ID (UUID) * @returns Null on success * * @example * ```typescript * await apiService.remove('123e4567-e89b-12d3-a456-426614174000'); * ``` */ remove(id: string): Promise<ApiResponse<null>>; /** * Get list of available dashboard modules * * @returns List of dashboard modules with multi-language labels * * @example * ```typescript * const modules = await apiService.getModules(); * // [{ value: 'MARKETING', label: { vi: 'Marketing', en: 'Marketing' } }, ...] * ``` */ getModules(): Promise<ApiResponse<DashboardModuleItem[]>>; /** * Get API statistics * * @returns Statistics and overview information about API configurations * * @example * ```typescript * const stats = await apiService.getStatistics(); * console.log(stats.result.totalApis); * console.log(stats.result.apisByMethod); * ``` */ getStatistics(): Promise<ApiResponse<ApiStatisticsResponse>>; } /** * Service for managing Page Templates * Maps to: PageTemplateController (page-template.controller.ts) * Base path: /dashboard-generic/page-templates */ declare class PageTemplateService { private readonly httpClient; private readonly basePath; constructor(httpClient: HttpClient); /** * Create a new Page Template * * @param data - Page template creation data * @returns Created page template * * @example * ```typescript * const template = await pageTemplateService.create({ * name: 'Customer Dashboard', * code: 'export default function Page({ apis }) { return <div>Hello</div>; }', * description: 'Dashboard for customer analytics', * tags: ['customer', 'dashboard'], * apiIds: ['123e4567-e89b-12d3-a456-426614174000'], * }); * ``` */ create(data: CreatePageTemplateRequest): Promise<ApiResponse<PageTemplateResponse>>; /** * Get all Page Templates with pagination and filtering * * @param query - Query parameters for filtering and pagination * @returns Paginated list of page templates * * @example * ```typescript * const result = await pageTemplateService.findAll({ * page: 1, * limit: 10, * status: 'active', * type: 'USER', * }); * ``` */ findAll(query?: QueryPageTemplateRequest): Promise<ApiResponse<PaginatedResult<PageTemplateResponse>>>; /** * Get Page Template by ID * * @param id - Page template ID (UUID) * @returns Page template details * * @example * ```typescript * const template = await pageTemplateService.findOne('123e4567-e89b-12d3-a456-426614174000'); * ``` */ findOne(id: string): Promise<ApiResponse<PageTemplateResponse>>; /** * Update Page Template * * @param id - Page template ID (UUID) * @param data - Update data * @returns Updated page template * * @example * ```typescript * const updated = await pageTemplateService.update('123e4567-e89b-12d3-a456-426614174000', { * name: 'Updated Dashboard', * code: 'export default function Page({ apis }) { return <div>Updated</div>; }', * }); * ``` */ update(id: string, data: UpdatePageTemplateRequest): Promise<ApiResponse<PageTemplateResponse>>; /** * Rename Page Template * * @param id - Page template ID (UUID) * @param name - New name for the template * @returns Updated page template * * @example * ```typescript * const renamed = await pageTemplateService.rename('123e4567-e89b-12d3-a456-426614174000', 'New Dashboard Name'); * ``` */ rename(id: string, name: string): Promise<ApiResponse<PageTemplateResponse>>; /** * Delete Page Template * * @param id - Page template ID (UUID) * @returns Null on success * * @example * ```typescript * await pageTemplateService.remove('123e4567-e89b-12d3-a456-426614174000'); * ``` */ remove(id: string): Promise<ApiResponse<null>>; /** * Associate APIs with a page template * * @param id - Page template ID (UUID) * @param apiIds - List of API IDs to associate * @returns Null on success * * @example * ```typescript * await pageTemplateService.associateApis('123e4567-e89b-12d3-a456-426614174000', [ * '456e7890-e89b-12d3-a456-426614174001', * '789e0123-e89b-12d3-a456-426614174002', * ]); * ``` */ associateApis(id: string, apiIds: string[]): Promise<ApiResponse<null>>; /** * Create Page Template from System Template * * @param templateId - System template ID (UUID) to copy from * @param customization - Optional customization for the new template * @returns Created page template * * @example * ```typescript * const template = await pageTemplateService.createFromTemplate( * '123e4567-e89b-12d3-a456-426614174000', * { name: 'My Custom Dashboard', description: 'Customized version' } * ); * ``` */ createFromTemplate(templateId: string, customization?: CreateFromTemplateRequest): Promise<ApiResponse<PageTemplateResponse>>; /** * Create Page Template with Template Data * * @param data - Template creation request with templateData structure * @returns Created page template * * @example * ```typescript * const template = await pageTemplateService.createWithTemplateData({ * templateData: { * name: 'Customer Dashboard', * code: 'export default function Page({ apis }) { return <div>Dashboard</div>; }', * description: 'A comprehensive dashboard', * }, * apiIds: ['123e4567-e89b-12d3-a456-426614174000'], * userCustomToolIds: ['789e0123-e89b-12d3-a456-426614174000'], * }); * ``` */ createWithTemplateData(data: CreateTemplateWithDataRequest): Promise<ApiResponse<PageTemplateResponse>>; } /** * Service for executing dashboard APIs and resources * Maps to: ExecuteApiController (execute-api.controller.ts) * Base path: /dashboard-generic/execute */ declare class ExecuteApiService { private readonly httpClient; private readonly basePath; constructor(httpClient: HttpClient); /** * Execute multiple dashboard APIs * * @param request - Execute API request with list of APIs * @returns Execution results for each API * * @example * ```typescript * const result = await executeApiService.execute({ * apis: [ * { * module: 'BUSINESS', * code: 'BUSINESS_REVENUE_OVERVIEW', * type: 'overview', * begin: 1704067200000, * end: 1735689600000, * }, * { * module: 'BUSINESS', * code: 'BUSINESS_REVENUE_PIECHART', * type: 'piechart', * begin: 1704067200000, * end: 1735689600000, * }, * ], * }); * ``` */ execute(request: ExecuteApiRequest): Promise<ApiResponse<ExecuteApiResponse>>; /** * Execute resources (single or batch) * Supports unified resourceId format and legacy format * * Resource ID Format: "prefix:uuid" * - pta:uuid - PageTemplateApiEntity * - api:uuid - API Entity * - tool:uuid - Custom Tool * * @param request - Execute resource request * @returns Array of execution results * * @example Single execution with unified resourceId * ```typescript * const result = await executeApiService.executeResource({ * resourceId: 'api:660e8400-e29b-41d4-a716-446655440001', * parameters: { * query_param: { filter: 'recent' }, * body: { name: 'Test' }, * }, * }); * ``` * * @example Batch execution * ```typescript * const result = await executeApiService.executeResource({ * resources: [ * { * resourceId: 'pta:550e8400-e29b-41d4-a716-446655440000', * parameters: { query_param: { page: 1 } }, * }, * { * resourceId: 'api:660e8400-e29b-41d4-a716-446655440001', * parameters: { query_param: { limit: 20 } }, * }, * { * resourceId: 'tool:770e8400-e29b-41d4-a716-446655440002', * integrationId: '880e8400-e29b-41d4-a716-446655440003', * parameters: { body: { name: 'Test' } }, * }, * ], * }); * ``` * * @example Legacy format (deprecated) * ```typescript * const result = await executeApiService.executeResource({ * pageTemplateApiId: '550e8400-e29b-41d4-a716-446655440000', * parameters: { query_param: { page: 1, limit: 10 } }, * }); * ``` */ executeResource(request: ExecuteResourceRequest): Promise<ApiResponse<ResourceExecutionResult[]>>; /** * Helper: Execute single API resource * * @param apiId - API entity ID * @param parameters - Input parameters * @returns Execution result */ executeApi(apiId: string, parameters?: Record<string, unknown>): Promise<ApiResponse<ResourceExecutionResult[]>>; /** * Helper: Execute single PageTemplateApi resource * * @param pageTemplateApiId - PageTemplateApi entity ID * @param parameters - Input parameters * @returns Execution result */ executePageTemplateApi(pageTemplateApiId: string, parameters?: Record<string, unknown>): Promise<ApiResponse<ResourceExecutionResult[]>>; /** * Helper: Execute single Custom Tool resource * * @param customToolId - Custom tool ID * @param integrationId - Integration ID for OAuth * @param parameters - Input parameters * @returns Execution result */ executeCustomTool(customToolId: string, integrationId: string, parameters?: Record<string, unknown>): Promise<ApiResponse<ResourceExecutionResult[]>>; } /** * Service for AI-powered Page Generation * Maps to: AiPageGeneratorController (ai-page-generator.controller.ts) * Base path: /dashboard-generic/ai-page-generator */ declare class AiPageGeneratorService { private readonly httpClient; private readonly basePath; constructor(httpClient: HttpClient); /** * Generate page template from AI using API definitions * * Workflow: * 1. Lấy thông tin chi tiết của APIs theo IDs * 2. AI phân tích API schemas và tạo React code phù hợp * 3. Generate code với React Live compatible code * 4. Nếu isSave = TRUE: Lưu template vào database * 5. Nếu isSave = FALSE: Chỉ trả về code để preview * * Processing Time: 30-120 giây (tùy độ phức tạp) * * @param request - Generate page request * @returns Generated page template response * * @example Generate from existing PageTemplate * ```typescript * const result = await aiPageGeneratorService.generate({ * pageTemplateId: '123e4567-e89b-12d3-a456-426614174000', * prompt: 'Tạo dashboard với line chart hiển thị doanh thu theo thời gian', * isSave: 'FALSE', * }); * ``` * * @example Generate with APIs * ```typescript * const result = await aiPageGeneratorService.generate({ * apiIds: ['123e4567-e89b-12d3-a456-426614174000'], * prompt: 'Tạo dashboard với line chart hiển thị doanh thu theo thời gian', * pattern: 'self-contained', * isSave: 'FALSE', * }); * ``` * * @example Generate and save template * ```typescript * const result = await aiPageGeneratorService.generate({ * apiIds: ['456e7890-e89b-12d3-a456-426614174001'], * prompt: 'Tạo trang quản lý danh sách khách hàng với bảng dữ liệu', * pattern: 'self-contained', * isSave: 'TRUE', * name: 'Quản Lý Khách Hàng', * description: 'Trang quản lý danh sách khách hàng', * }); * ``` */ generate(request: GeneratePageFromAiRequest): Promise<ApiResponse<GeneratePageFromAiResponse>>; /** * Generate dashboard from AI with dynamic component builder * * Khác biệt với generate(): * - Sử dụng buildDynamicComponentsContent() thay vì buildComponentsContent() * - Hỗ trợ React 18, TypeScript 5.7, Tailwind CSS 3.3, Recharts 2.15, React Hook Form 7.60 * - Tập trung vào dashboard patterns với charts, tables, forms * * Processing Time: 30-120 giây (tùy độ phức tạp) * * @param request - Generate dashboard request * @returns Generated dashboard template response * * @example Generate dashboard from existing PageTemplate * ```typescript * const result = await aiPageGeneratorService.generateDashboard({ * pageTemplateId: '123e4567-e89b-12d3-a456-426614174000', * prompt: 'Tạo dashboard với line chart hiển thị doanh thu theo thời gian', * isSave: 'FALSE', * }); * ``` * * @example Generate dashboard with APIs and Custom Tools * ```typescript * const result = await aiPageGeneratorService.generateDashboard({ * apiIds: ['123e4567-e89b-12d3-a456-426614174000'], * userCustomToolIds: ['789e0123-e89b-12d3-a456-426614174000'], * prompt: 'Tạo dashboard kết hợp APIs và Custom Tools với charts và tables', * isSave: 'FALSE', * }); * ``` * * @example Generate and save dashboard template * ```typescript * const result = await aiPageGeneratorService.generateDashboard({ * apiIds: ['456e7890-e89b-12d3-a456-426614174001'], * prompt: 'Tạo trang quản lý danh sách khách hàng với bảng dữ liệu', * isSave: 'TRUE', * name: 'Quản Lý Khách Hàng Dashboard', * description: 'Dashboard quản lý danh sách khách hàng với dynamic components', * }); * ``` */ generateDashboard(request: GeneratePageFromAiRequest): Promise<ApiResponse<GeneratePageFromAiResponse>>; /** * Helper: Generate page with self-contained pattern * Component tự fetch data với useExecuteResource hook * * @param apiIds - List of API IDs * @param prompt - AI prompt * @param options - Additional options */ generateSelfContained(apiIds: string[], prompt: string, options?: { name?: string; description?: string; isSave?: 'TRUE' | 'FALSE'; }): Promise<ApiResponse<GeneratePageFromAiResponse>>; /** * Helper: Generate page with props-driven pattern * Component nhận data từ props, không tự fetch data * * @param apiIds - List of API IDs * @param prompt - AI prompt * @param options - Additional options */ generatePropsDriven(apiIds: string[], prompt: string, options?: { name?: string; description?: string; isSave?: 'TRUE' | 'FALSE'; }): Promise<ApiResponse<GeneratePageFromAiResponse>>; /** * Helper: Generate page with all-in-one pattern * Component tự fetch data với pageTemplateApiId * * @param apiIds - List of API IDs * @param prompt - AI prompt * @param options - Additional options */ generateAllInOne(apiIds: string[], prompt: string, options?: { name?: string; description?: string; isSave?: 'TRUE' | 'FALSE'; }): Promise<ApiResponse<GeneratePageFromAiResponse>>; } /** * Dashboard Generic Module Client * * Provides access to all dashboard-generic services: * - ApiService: Manage API configurations * - PageTemplateService: Manage page templates * - ExecuteApiService: Execute dashboard APIs and resources * - AiPageGeneratorService: AI-powered page generation */ declare class DashboardGenericModule { /** Service for managing API configurations */ readonly api: ApiService; /** Service for managing page templates */ readonly pageTemplate: PageTemplateService; /** Service for executing dashboard APIs and resources */ readonly execute: ExecuteApiService; /** Service for AI-powered page generation */ readonly aiPageGenerator: AiPageGeneratorService; constructor(httpClient: HttpClient); } /** * Create Dashboard Generic Module instance * * @param config - HTTP client configuration * @returns DashboardGenericModule instance * * @example * ```typescript * import { createDashboardGenericModule } from '@redai/api-sdk/dashboard-generic'; * * const dashboardModule = createDashboardGenericModule({ * baseUrl: 'https://api.example.com', * }); * * // Set auth token * dashboardModule.setAuthToken('your-jwt-token'); * * // Use services * const apis = await dashboardModule.api.findAll({ page: 1, limit: 10 }); * const templates = await dashboardModule.pageTemplate.findAll(); * ``` */ declare function createDashboardGenericModule(config: HttpClientConfig): DashboardGenericModule & { setAuthToken: (token: string) => void; clearAuthToken: () => void; }; export { type ChartMetricGroup as $, type ApiResponse as A, type CustomToolRef as B, type CacheConfig as C, DashboardGenericModule as D, type CreatePageTemplateRequest as E, type UpdatePageTemplateRequest as F, type QueryPageTemplateRequest as G, type HttpClientConfig as H, type I18nLabel as I, type RenamePageTemplateRequest as J, type AssociateApisRequest as K, type LayoutType as L, type CreateFromTemplateRequest as M, type CreateTemplateWithDataRequest as N, type PageTemplateResponse as O, type PaginatedResult as P, type QueryParams as Q, type ResourceType as R, SortDirection as S, type TemplateData as T, type UpdateApiRequest as U, type ChartFilter as V, type ChartGroupBy as W, type ChartAggregate as X, type ChartColumn as Y, type ChartFunnelStep as Z, type ChartMetric as _, HttpClient as a, type GenericChartConfig as a0, type ExecuteApiItem as a1, type ExecuteApiRequest as a2, type ExecuteApiResultItem as a3, type ExecuteApiResponse as a4, type ResourceExecutionItem as a5, type ExecuteResourceRequest as a6, type ResourceExecutionResult as a7, type ExecuteResourceResponse as a8, type GenerationPattern as a9, type GeneratePageFromAiRequest as aa, type ValidationError as ab, type SavedTemplateInfo as ac, type GeneratePageFromAiResponse as ad, type GeneratePageHtmlFromAiResponse as ae, ApiService as af, PageTemplateService as ag, ExecuteApiService as ah, AiPageGeneratorService as ai, type HttpMethod as b, createDashboardGenericModule as c, type ApiStatus as d, type PageTemplateStatus as e, PageTemplateType as f, DashboardModule as g, DashboardChartType as h, type AuthType as i, RESOURCE_PREFIX as j, type ResourcePrefix as k, type Schema as l, type RateLimitConfig as m, type AuthConfig as n, type RetryConfig as o, type CreateApiRequest as p, type QueryApiRequest as q, type ApiConfigResponse as r, type DashboardModuleItem as s, type ApiStatisticsResponse as t, type LayoutConfig as u, type SeoMeta as v, type PageConfig as w, type Dependencies as x, type UsageStats as y, type PreviewData as z };