import {z} from 'zod' export type ClientDataForBudget = {nombre: string, apellido: string, numero_documento_identidad?: (string | null) | undefined, dni?: (string | null) | undefined, direccion?: (string | null) | undefined, localidad?: (string | null) | undefined, cp?: (string | null) | undefined, provincia_id: number, email: string, telefono?: (string | null) | undefined, telefono_comercial?: (string | null) | undefined, dia_respuesta?: (string | null) | undefined}; export type BatterySelection = {bateria_id: number, cantidad?: number | undefined}; export type BudgetCalculationRequest = {solo_bateria?: boolean | undefined, consumo_mes_kwh?: number | undefined, provincia: number, presupuesto_id?: (number | null) | undefined, panel_id?: (number | null) | undefined, micro_inversor_id?: (number | null) | undefined, baterias?: (BatterySelection | null) | undefined, extras_ids?: Array | undefined, metros_cableado?: number | undefined, estructura_id?: (number | null) | undefined, num_paneles_sin_pergola?: number | undefined, ground_type_id?: (number | null) | undefined, forma_pago?: (number | null) | undefined, opcion_contado_id?: (number | null) | undefined, meses_financiacion?: (number | null) | undefined, entidad_financiera?: (string | null) | undefined, contado_financiacion?: (number | null) | undefined, con_backup?: boolean | undefined}; export type SaveBudgetRequest = {client_data: ClientDataForBudget, calculation_data: BudgetCalculationRequest, selected_option?: (number | null) | undefined, enviar_hubspot?: boolean | undefined, presupuesto_id?: (number | null) | undefined, comercial_id?: (number | null) | undefined, guarda_opcion_cliente_test?: boolean | undefined}; export type CreateApiApiBudgetSaveArgs = {body: SaveBudgetRequest}; export type CreateApiApiBudgetSaveOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const saveBudgetResponse = z.object({success: z.boolean(), message: z.string(), budget_id: z.number().int().nullable().optional(), hubspot_contact_id: z.string().nullable().optional(), hubspot_warning: z.string().nullable().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 }; /** * Save Budget * * POST /api/budget/save */ export const createApiApiBudgetSave = async (args: CreateApiApiBudgetSaveArgs, options: CreateApiApiBudgetSaveOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/budget/save${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(saveBudgetResponse, await res.json()) };