import {z} from 'zod' export type AggregateRequest = {group_by_fields: Array, aggregate_field?: (string | null) | undefined, match_filter_dict?: (string | null) | undefined, sort_dict?: (string | null) | undefined, page_size?: number | undefined, page_num?: number | undefined}; export type CreateApiCrmOrdersAggregateArgs = {body: AggregateRequest}; export type CreateApiCrmOrdersAggregateOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const aggregateGroup = z.object({group_by: z.string().optional(), group_by_values: z.record(z.string(), z.unknown()).nullable().optional(), count: z.number().int().optional(), total_value: z.number().nullable().optional(), avg_value: z.number().nullable().optional(), max_value: z.number().nullable().optional(), min_value: z.number().nullable().optional(), entity_ids_list: z.array(z.unknown()).nullable().optional()}); export const aggregateResponse = z.object({groups: z.array(aggregateGroup).optional(), total_groups: z.number().int().optional(), aggregate_field: z.string().nullable().optional(), group_by_fields: z.array(z.string()).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 }; /** * Aggregate Orders * * POST /crm/orders/aggregate */ export const createApiCrmOrdersAggregate = async (args: CreateApiCrmOrdersAggregateArgs, options: CreateApiCrmOrdersAggregateOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("Authorization", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/crm/orders/aggregate${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(aggregateResponse, await res.json()) };