import {z} from 'zod' export type GetApiApiBudgetAnalyticsArgs = {fecha_inicio: string, fecha_fin: string, comercial_ids?: (Array | null) | undefined, estado_filtros?: (Array | null) | undefined}; export type GetApiApiBudgetAnalyticsOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const kpisResponse = z.object({total_presupuestos: z.number().int(), total_pedidos: z.number().int(), total_importe_pedidos: z.number(), tasa_conversion: z.number(), presupuestos_periodo_anterior: z.number().int(), pedidos_periodo_anterior: z.number().int(), importe_pedidos_periodo_anterior: z.number(), variacion_presupuestos: z.number().nullable(), variacion_pedidos: z.number().nullable(), variacion_importe_pedidos: z.number().nullable(), variacion_conversion: z.number().nullable(), importe_medio_pedido: z.number().optional()}); export const mesRow = z.object({mes: z.string(), presupuestos: z.number().int(), pedidos: z.number().int(), tasa_conversion: z.number()}); export const estadoRow = z.object({estado: z.string(), color: z.string().nullable(), total: z.number().int()}); export const comercialRow = z.object({comercial_id: z.number().int(), nombre: z.string(), presupuestos: z.number().int(), pedidos: z.number().int(), tasa_conversion: z.number()}); export const tablaAgregadaRow = z.object({mes: z.string(), comercial: z.string(), presupuestos: z.number().int(), pedidos: z.number().int(), tasa_conversion: z.number()}); export const funnelStep = z.object({tipo_estado: z.string(), total: z.number().int(), porcentaje: z.number()}); export const estadoGranularRow = z.object({tipo_estado: z.string(), estado: z.string(), color: z.string().nullable(), total: z.number().int()}); export const comercialFunnelRow = z.object({comercial_id: z.number().int(), nombre: z.string(), total_visitas: z.number().int(), en_estado_visita: z.number().int(), presupuestado: z.number().int(), en_estado_pedido: z.number().int(), pedidos_reales: z.number().int(), importe_total: z.number(), importe_medio_pedido: z.number(), ratio_visita_presupuesto: z.number(), ratio_presupuesto_pedido: z.number(), ratio_total: z.number()}); export const analyticsResponse = z.object({kpis: kpisResponse, por_mes: z.array(mesRow), por_estado: z.array(estadoRow), por_comercial: z.array(comercialRow), tabla_agregada: z.array(tablaAgregadaRow), funnel: z.array(funnelStep).optional(), por_estado_granular: z.array(estadoGranularRow).optional(), por_comercial_funnel: z.array(comercialFunnelRow).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 Budget Analytics * * GET /api/budget/analytics */ export const getApiApiBudgetAnalytics = async (args: GetApiApiBudgetAnalyticsArgs, options: GetApiApiBudgetAnalyticsOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.fecha_inicio != null) query.append("fecha_inicio", String(args.fecha_inicio)) if (args.fecha_fin != null) query.append("fecha_fin", String(args.fecha_fin)) for (const item of args.comercial_ids ?? []) query.append("comercial_ids", String(item)) for (const item of args.estado_filtros ?? []) query.append("estado_filtros", String(item)) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/budget/analytics${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(analyticsResponse, await res.json()) };