import {z} from 'zod' export type MetricParams = {createdAfter?: string | undefined, createdBefore?: string | undefined, calculationInterval?: ('day' | 'week' | 'month' | 'quarter' | 'year') | undefined, userIds?: Array | undefined, transactionTypes?: (Array<'onramp' | 'offramp' | 'transfer'>) | undefined, transactionStatuses?: (Array<'AWAITING_FUNDS' | 'COMPLETED' | 'CRYPTO_FAILED' | 'CRYPTO_INITIATED' | 'CRYPTO_PENDING' | 'FAILED' | 'FIAT_FAILED' | 'FIAT_INITIATED' | 'FIAT_PENDING' | 'FIAT_PROCESSED' | 'FIAT_RETURNED' | 'INITIATED' | 'NOT_INITIATED' | 'PENDING' | 'QUOTE_FAILED' | 'REJECTED'>) | undefined, breakdowns?: (Array<'transactionType' | 'transactionStatus' | 'userId'>) | undefined, limit?: number | undefined} | {[key: string]: unknown}; export type PreviewMetricRequest = {template: 'GROSS_VOLUME' | 'TRANSACTION_COUNT' | 'NEW_USERS', params: MetricParams}; export type CreateApiV2ReportingMetricsPreviewArgs = {body: PreviewMetricRequest}; export type CreateApiV2ReportingMetricsPreviewOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const metricCalculationMetadata = z.object({template: z.enum(["GROSS_VOLUME", "TRANSACTION_COUNT", "NEW_USERS"]).optional(), recordCount: z.number().int().optional(), projectedRowCount: z.number().int().nullable().optional(), filledCount: z.number().int().optional(), calculationInterval: z.enum(["day", "week", "month", "quarter", "year"]).optional(), dateRange: z.object({start: z.string().optional(), end: z.string().optional()}).optional(), filters: z.record(z.string(), z.unknown()).optional(), breakdowns: z.object({dimensions: z.array(z.enum(["transactionType", "transactionStatus", "userId"])).optional(), dimensionCounts: z.record(z.string(), z.number().int()).optional()}).nullable().optional(), metric: z.string().nullable().optional()}); export const metricCalculationResponse = z.object({status: z.literal("success").optional(), data: z.array(z.object({periodStart: z.string().optional(), grossVolume: z.number().optional(), grossVolumeUsd: z.number().optional(), transactionCount: z.number().optional(), newUserCount: z.number().optional(), transactionType: z.enum(["onramp", "offramp", "transfer"]).optional(), transactionStatus: z.enum(["AWAITING_FUNDS", "COMPLETED", "CRYPTO_FAILED", "CRYPTO_INITIATED", "CRYPTO_PENDING", "FAILED", "FIAT_FAILED", "FIAT_INITIATED", "FIAT_PENDING", "FIAT_PROCESSED", "FIAT_RETURNED", "INITIATED", "NOT_INITIATED", "PENDING", "QUOTE_FAILED", "REJECTED"]).optional(), userId: z.string().optional()}).and(z.record(z.string(), z.unknown()))).optional(), metadata: metricCalculationMetadata.optional()}); 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 }; /** * Preview Metric Results * * POST /v2/reporting/metrics/preview */ export const createApiV2ReportingMetricsPreview = async (args: CreateApiV2ReportingMetricsPreviewArgs, options?: CreateApiV2ReportingMetricsPreviewOptions) => { const {baseUrl = "https://production.hifibridge.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/reporting/metrics/preview${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(metricCalculationResponse, await res.json()) };