import { rpcOrEmptyArray, rpcOrValue } from './rpc.uts' export type CustomReportListItem = { id: string title: string description: string period: string updated_at: string } export type CreateCustomReportParams = { title: string description: string period: string metrics: Array chartType: string } export type UpdateCustomReportParams = { reportId: string title: string description: string | null period: string | null } function safeString(v: any): string { return v != null ? `${v}` : '' } // 改造:不再直查 analytics_reports 表,统一通过 RPC 获取当前用户的报表列表 export async function listCustomReports(ownerUserId: string): Promise> { const rows = await rpcOrEmptyArray('rpc_get_custom_reports', {} as any) const list: Array = [] for (let i = 0; i < rows.length; i++) { const r: any = rows[i] list.push({ id: safeString(r.getAny?.('id') ?? r.getString?.('id')), title: safeString(r.getAny?.('title') ?? r.getString?.('title')), description: safeString(r.getAny?.('description') ?? r.getString?.('description')), // 兼容旧 UI 字段:custom-report 页面里可能还在用 period 字段 period: '', updated_at: safeString(r.getAny?.('updated_at') ?? r.getString?.('updated_at')) }) } return list } // 改造:RPC 参数改为 p_definition(JSONB),承载 period/metrics/chartType export async function createCustomReport(params: CreateCustomReportParams): Promise { const definition = { period: params.period, metrics: params.metrics, chartType: params.chartType || 'line' } const data = await rpcOrValue('rpc_create_custom_report', { p_title: params.title, p_description: params.description || '', p_definition: definition } as any) if (data == null) { throw new Error('保存失败:未返回报表ID') } return `${data}` } export async function updateCustomReport(params: UpdateCustomReportParams): Promise { // 注意:旧 UI 只传 title/description/period,这里把 period 合并进 definition const definition = { period: params.period } await rpcOrValue('rpc_update_custom_report', { p_report_id: params.reportId, p_title: params.title, p_description: params.description, p_definition: definition } as any) return true } export async function deleteCustomReport(reportId: string): Promise { await rpcOrValue('rpc_delete_custom_report', { p_report_id: reportId } as any) return true }