import {z} from 'zod' export type GetApiAnalyticsChartsChartCodeArgs = {chart_code: 'proceeds' | 'active-subscriptions' | 'paid-subscriptions-movement' | 'users-overview' | 'free-trials' | 'active-trials' | 'trials-movement' | 'user-to-trial' | 'trial-to-paid' | 'user-to-paid' | 'sales' | 'refunds' | 'refund-rate' | 'arppu' | 'arpu' | 'trial-cancellation' | 'subscription-cancellation' | 'subscriptions-overview' | 'new-subscriptions' | 'mrr' | 'arr' | 'mrr-movement' | 'arr-movement' | 'user-to-trial-conversion' | 'subscription-cancellation-rate', from?: number | undefined, to?: number | undefined, unit?: ('hour' | 'day' | 'week' | 'month') | undefined, environment?: (0 | 1) | undefined, max_series?: number | undefined, segmentation?: string | undefined, currency?: string | undefined, 'filter[][]'?: Array | undefined}; export type GetApiAnalyticsChartsChartCodeOptions = {baseUrl?: string | undefined, secretAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const v4AnalyticsSeriesDataPoint = z.object({start_time: z.number().int(), value: z.number()}); export const v4AnalyticsSeries = z.object({label: z.string(), total: z.number().nullable().optional(), totalPrev: z.number().nullable().optional(), totalWeight: z.number().nullable().optional(), totalPrevWeight: z.number().nullable().optional(), totalIgnoreInFinal: z.boolean().nullable().optional(), data: z.array(v4AnalyticsSeriesDataPoint)}); export const v4AnalyticsChart = z.object({object: z.literal("analytics_chart"), url: z.string(), code: z.string(), from: z.number().int(), to: z.number().int(), unit: z.enum(["hour", "day", "week", "month"]), environment: z.union([z.literal(0), z.literal(1)]), currency: z.string().optional(), measure: z.enum(["usd", "count", "percent"]), totalType: z.enum(["sum", "wavg"]), seriesRelation: z.enum(["partsOfWhole", "independent"]), maxSeries: z.number().int(), horizontalLabelType: z.string().optional(), segmentation: z.string().nullable().optional(), summarySeries: v4AnalyticsSeries.optional(), series: z.array(v4AnalyticsSeries)}); 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 }; /** * Get analytics chart data * * GET /analytics/charts/{chart_code} */ export const getApiAnalyticsChartsChartCode = async (args: GetApiAnalyticsChartsChartCodeArgs, options?: GetApiAnalyticsChartsChartCodeOptions) => { const {baseUrl = "https://api.qonversion.io/v4", fetch: fetchFn = fetch, secretAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args.unit != null) query.append("unit", String(args.unit)) if (args.environment != null) query.append("environment", String(args.environment)) if (args.max_series != null) query.append("max_series", String(args.max_series)) if (args.segmentation != null) query.append("segmentation", String(args.segmentation)) if (args.currency != null) query.append("currency", String(args.currency)) for (const item of args['filter[][]'] ?? []) query.append("filter[][]", String(item)) if (secretAuth !== undefined) headers.set('authorization', `Bearer ${secretAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/analytics/charts/${encodeURIComponent(String(args.chart_code))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(v4AnalyticsChart, await res.json()) };