import {z} from 'zod' export type SchedulerFormat = 'csv' | 'xlsx' | 'image' | 'gsheets' | 'pdf'; export type SchedulerCsvOptions = {xlsxFileLayout?: ('zip' | 'workbook') | undefined, exportPivotedData?: boolean | undefined, asAttachment?: boolean | undefined, limit: number | 'table' | 'all', formatted: boolean}; export type SchedulerImageOptions = {pagePerTab?: boolean | undefined, withPdf?: boolean | undefined}; export type SchedulerGsheetsOptions = {tabName?: string | undefined, url: string, gdriveOrganizationName: string, gdriveName: string, gdriveId: string}; export type SchedulerPdfOptions = {pagePerTab?: boolean | undefined}; export type SchedulerOptions = SchedulerCsvOptions | SchedulerImageOptions | SchedulerGsheetsOptions | SchedulerPdfOptions; export type ThresholdOperator = 'greaterThan' | 'lessThan' | 'increasedBy' | 'decreasedBy'; export type ThresholdOptions = {value: number, fieldId: string, operator: ThresholdOperator}; export type NotificationFrequency = 'always' | 'once'; export type PickSchedulerSlackTargetChannel = {channel: string}; export type PickSchedulerMsTeamsTargetWebhook = {webhook: string}; export type PickSchedulerGoogleChatTargetGoogleChatWebhook = {googleChatWebhook: string}; export type PickSchedulerEmailTargetRecipient = {recipient: string}; export type CreateSchedulerTarget = PickSchedulerSlackTargetChannel | PickSchedulerMsTeamsTargetWebhook | PickSchedulerGoogleChatTargetGoogleChatWebhook | PickSchedulerEmailTargetRecipient; export type SchedulerAiAugmentation = {sourceThreadUuid: string | null, agentUuid: string, prompt: string, type: 'agent'} | {prompt: string, type: 'fast_model'}; export type PickCreateSchedulerAndTargetsExcludeKeyofCreateSchedulerAndTargetsSavedChartUuidOrDashboardUuidOrSavedSqlUuidOrCreatedBy = {name: string, slug?: string | undefined, timezone?: string | undefined, projectUuid?: (string | null) | undefined, cron: string, enabled: boolean, message?: string | undefined, format: SchedulerFormat, projectSchedulerTimezone?: string | undefined, appUuid: string | null, appName: string | null, options: SchedulerOptions, thresholds?: Array | undefined, notificationFrequency?: NotificationFrequency | undefined, includeLinks: boolean, projectName?: (string | null) | undefined, targets: Array, aiAugmentation?: (SchedulerAiAugmentation | null) | undefined}; export type CreateSchedulerAndTargetsWithoutIds = PickCreateSchedulerAndTargetsExcludeKeyofCreateSchedulerAndTargetsSavedChartUuidOrDashboardUuidOrSavedSqlUuidOrCreatedBy; export type CreateApiApiV1SavedChartUuidSchedulersArgs = {chartUuid: string, body: CreateSchedulerAndTargetsWithoutIds}; export type CreateApiApiV1SavedChartUuidSchedulersOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const notificationFrequency = z.enum(["always", "once"]); export const thresholdOperator = z.enum(["greaterThan", "lessThan", "increasedBy", "decreasedBy"]); export const thresholdOptions = z.object({value: z.number(), fieldId: z.string(), operator: thresholdOperator}); export const schedulerCsvOptions = z.object({xlsxFileLayout: z.enum(["zip", "workbook"]).optional(), exportPivotedData: z.boolean().optional(), asAttachment: z.boolean().optional(), limit: z.union([z.number(), z.enum(["table", "all"])]), formatted: z.boolean()}); export const schedulerImageOptions = z.object({pagePerTab: z.boolean().optional(), withPdf: z.boolean().optional()}); export const schedulerGsheetsOptions = z.object({tabName: z.string().optional(), url: z.string(), gdriveOrganizationName: z.string(), gdriveName: z.string(), gdriveId: z.string()}); export const schedulerPdfOptions = z.object({pagePerTab: z.boolean().optional()}); export const schedulerOptions = z.union([schedulerCsvOptions, schedulerImageOptions, schedulerGsheetsOptions, schedulerPdfOptions]); export const schedulerFormat = z.enum(["csv", "xlsx", "image", "gsheets", "pdf"]); export const parameterValue = z.union([z.string(), z.number(), z.array(z.string()), z.array(z.number())]); export const parametersValuesMap = z.record(z.string(), parameterValue); export const anyType = z.unknown(); export const filterOperator = z.enum(["isNull", "notNull", "equals", "notEquals", "startsWith", "endsWith", "include", "doesNotInclude", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "inThePast", "notInThePast", "inTheNext", "inTheCurrent", "notInTheCurrent", "inBetween", "notInBetween", "inPeriodToDate"]); export const fieldTarget = z.object({fieldId: z.string()}); export const filterRule = z.object({includeNull: z.boolean().optional(), values: z.array(anyType).optional(), operator: filterOperator, id: z.string(), target: fieldTarget, settings: anyType.optional(), disabled: z.boolean().optional(), required: z.boolean().optional(), caseSensitive: z.boolean().optional()}).and(z.record(z.string(), z.unknown())); export const filterGroupItem = z.union([z.lazy(() => filterGroup), filterRule]); export const orFilterGroup = z.object({or: z.array(filterGroupItem), id: z.string()}); export const andFilterGroup = z.object({and: z.array(filterGroupItem), id: z.string()}); export const filterGroup: z.ZodType = z.union([orFilterGroup, andFilterGroup]); export const filters = z.object({tableCalculations: filterGroup.optional(), metrics: filterGroup.optional(), dimensions: filterGroup.optional()}); export const schedulerResourceType = z.enum(["chart", "dashboard", "sqlChart", "app"]); export const logCounts = z.object({error: z.number(), completed: z.number(), started: z.number(), scheduled: z.number(), total: z.number()}); export const recordStringAnyType = z.record(z.string(), z.unknown()); export const schedulerRunStatus = z.enum(["completed", "partial_failure", "failed", "running", "scheduled"]); export const schedulerJobStatus = z.enum(["scheduled", "started", "completed", "error"]); export const schedulerRun = z.object({format: schedulerFormat, createdByUserName: z.string(), createdByUserUuid: z.string(), resourceName: z.string(), resourceUuid: z.string(), resourceType: schedulerResourceType, logCounts: logCounts, details: recordStringAnyType.nullable(), createdAt: z.string(), runStatus: schedulerRunStatus, status: schedulerJobStatus, scheduledTime: z.string(), schedulerName: z.string(), schedulerUuid: z.string(), runId: z.string()}); export const schedulerSlackTarget = z.object({channel: z.string(), schedulerUuid: z.string(), updatedAt: z.string(), createdAt: z.string(), schedulerSlackTargetUuid: z.string()}); export const schedulerEmailTarget = z.object({recipient: z.string(), schedulerUuid: z.string(), updatedAt: z.string(), createdAt: z.string(), schedulerEmailTargetUuid: z.string()}); export const schedulerMsTeamsTarget = z.object({webhook: z.string(), schedulerUuid: z.string(), updatedAt: z.string(), createdAt: z.string(), schedulerMsTeamsTargetUuid: z.string()}); export const schedulerGoogleChatTarget = z.object({googleChatWebhook: z.string(), schedulerUuid: z.string(), updatedAt: z.string(), createdAt: z.string(), schedulerGoogleChatTargetUuid: z.string()}); export const dimensionType = z.enum(["string", "number", "timestamp", "date", "boolean"]); export const dashboardFieldTarget = z.object({fallbackType: dimensionType.optional(), isSqlColumn: z.boolean().optional(), tableName: z.string(), fieldId: z.string()}); export const dashboardTileTarget = z.union([dashboardFieldTarget, z.literal(false)]); export const dashboardTileTargets = z.record(z.string(), dashboardTileTarget); export const dashboardFilterRule = z.object({includeNull: z.boolean().optional(), values: z.array(anyType).optional(), operator: filterOperator, id: z.string(), target: dashboardFieldTarget, settings: anyType.optional(), disabled: z.boolean().optional(), required: z.boolean().optional(), caseSensitive: z.boolean().optional(), lockedTabUuids: z.array(z.string()).optional(), requiredGroupId: z.string().optional(), singleValue: z.boolean().optional(), label: z.string().optional(), tileTargets: dashboardTileTargets.optional()}).and(z.record(z.string(), z.unknown())); export const schedulerAndTargets = z.union([z.object({projectName: z.string().nullable().optional(), projectUuid: z.string().nullable().optional(), includeLinks: z.boolean(), notificationFrequency: notificationFrequency.optional(), enabled: z.boolean(), thresholds: z.array(thresholdOptions).optional(), options: schedulerOptions, appName: z.string().nullable(), appUuid: z.string().nullable(), savedSqlName: z.string().nullable(), savedSqlUuid: z.string().nullable(), dashboardName: z.string().nullable(), dashboardUuid: z.string().nullable(), savedChartName: z.string().nullable(), savedChartUuid: z.string().nullable(), projectSchedulerTimezone: z.string().optional(), timezone: z.string().optional(), cron: z.string(), format: schedulerFormat, createdByName: z.string().nullable(), createdBy: z.string(), updatedAt: z.string(), createdAt: z.string(), message: z.string().optional(), name: z.string(), slug: z.string(), schedulerUuid: z.string(), parameters: parametersValuesMap.optional(), filters: filters.optional(), latestRun: schedulerRun.nullable().optional(), targets: z.array(z.union([schedulerSlackTarget, schedulerEmailTarget, schedulerMsTeamsTarget, schedulerGoogleChatTarget]))}), z.object({projectName: z.string().nullable().optional(), projectUuid: z.string().nullable().optional(), includeLinks: z.boolean(), notificationFrequency: notificationFrequency.optional(), enabled: z.boolean(), thresholds: z.array(thresholdOptions).optional(), options: schedulerOptions, appName: z.string().nullable(), appUuid: z.string().nullable(), savedSqlName: z.string().nullable(), savedSqlUuid: z.string().nullable(), dashboardName: z.string().nullable(), dashboardUuid: z.string().nullable(), savedChartName: z.string().nullable(), savedChartUuid: z.string().nullable(), projectSchedulerTimezone: z.string().optional(), timezone: z.string().optional(), cron: z.string(), format: schedulerFormat, createdByName: z.string().nullable(), createdBy: z.string(), updatedAt: z.string(), createdAt: z.string(), message: z.string().optional(), name: z.string(), slug: z.string(), schedulerUuid: z.string(), selectedTabs: z.array(z.string()).nullable(), customViewportWidth: z.number().optional(), parameters: parametersValuesMap.optional(), filters: z.array(dashboardFilterRule).optional(), latestRun: schedulerRun.nullable().optional(), targets: z.array(z.union([schedulerSlackTarget, schedulerEmailTarget, schedulerMsTeamsTarget, schedulerGoogleChatTarget]))}), z.object({projectName: z.string().nullable().optional(), projectUuid: z.string().nullable().optional(), includeLinks: z.boolean(), notificationFrequency: notificationFrequency.optional(), enabled: z.boolean(), thresholds: z.array(thresholdOptions).optional(), options: schedulerOptions, appName: z.string().nullable(), appUuid: z.string().nullable(), savedSqlName: z.string().nullable(), savedSqlUuid: z.string().nullable(), dashboardName: z.string().nullable(), dashboardUuid: z.string().nullable(), savedChartName: z.string().nullable(), savedChartUuid: z.string().nullable(), projectSchedulerTimezone: z.string().optional(), timezone: z.string().optional(), cron: z.string(), format: schedulerFormat, createdByName: z.string().nullable(), createdBy: z.string(), updatedAt: z.string(), createdAt: z.string(), message: z.string().optional(), name: z.string(), slug: z.string(), schedulerUuid: z.string(), latestRun: schedulerRun.nullable().optional(), targets: z.array(z.union([schedulerSlackTarget, schedulerEmailTarget, schedulerMsTeamsTarget, schedulerGoogleChatTarget]))}), z.object({projectName: z.string().nullable().optional(), projectUuid: z.string().nullable().optional(), includeLinks: z.boolean(), notificationFrequency: notificationFrequency.optional(), enabled: z.boolean(), thresholds: z.array(thresholdOptions).optional(), options: schedulerOptions, appName: z.string().nullable(), appUuid: z.string().nullable(), savedSqlName: z.string().nullable(), savedSqlUuid: z.string().nullable(), dashboardName: z.string().nullable(), dashboardUuid: z.string().nullable(), savedChartName: z.string().nullable(), savedChartUuid: z.string().nullable(), projectSchedulerTimezone: z.string().optional(), timezone: z.string().optional(), cron: z.string(), format: schedulerFormat, createdByName: z.string().nullable(), createdBy: z.string(), updatedAt: z.string(), createdAt: z.string(), message: z.string().optional(), name: z.string(), slug: z.string(), schedulerUuid: z.string(), latestRun: schedulerRun.nullable().optional(), targets: z.array(z.union([schedulerSlackTarget, schedulerEmailTarget, schedulerMsTeamsTarget, schedulerGoogleChatTarget]))})]); export const apiCreateSavedChartSchedulerResponse = z.object({results: schedulerAndTargets, status: z.literal("ok")}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create saved chart scheduler * * POST /api/v1/saved/{chartUuid}/schedulers */ export const createApiApiV1SavedChartUuidSchedulers = async (args: CreateApiApiV1SavedChartUuidSchedulersArgs, options: CreateApiApiV1SavedChartUuidSchedulersOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/saved/${encodeURIComponent(String(args.chartUuid))}/schedulers${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(apiCreateSavedChartSchedulerResponse, await res.json()) };