import {z} from 'zod' export type StatsAggregationType = 'DAY' | 'WEEK' | 'MONTH'; export type GetApiApiStatsArgs = {start_date?: (string | null) | undefined, end_date?: (string | null) | undefined, aggregation?: (StatsAggregationType | null) | undefined}; export type GetApiApiStatsOptions = {baseUrl?: string | undefined, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const statsAggregationType = z.enum(["DAY", "WEEK", "MONTH"]); export const actionType = z.enum(["DOCUMENT_SENT", "DOCUMENT_RECEIVED"]); export const actionStats = z.object({action: actionType, stat_date: z.string(), count: z.number().int().gte(0)}); export const statsResponse = z.object({tenant_id: z.string(), period_start: z.string(), period_end: z.string(), aggregation: statsAggregationType, actions: z.array(actionStats), total_days: z.number().int().gte(1), average_daily_usage: z.number().gte(0), budget_estimation_days: z.number().gte(0).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 }; /** * Get Usage Statistics * * GET /api/stats */ export const getApiApiStats = async (args: GetApiApiStatsArgs, options?: GetApiApiStatsOptions) => { const {baseUrl = "https://api.e-invoice.be", fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.start_date != null) query.append("start_date", String(args.start_date)) if (args.end_date != null) query.append("end_date", String(args.end_date)) if (args.aggregation != null) query.append("aggregation", String(args.aggregation)) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/stats${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(statsResponse, await res.json()) };