import {z} from 'zod' export type ClientDataForOrder = {nombre?: (string | null) | undefined, apellido?: (string | null) | undefined, 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 | null) | undefined, email?: (string | null) | undefined, telefono?: (string | null) | undefined, telefono_comercial?: (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 OrderDataForHubSpot = {dni_foto_por_delante?: (string | Array<{[key: string]: string}> | null) | undefined, dni_detras?: (string | Array<{[key: string]: string}> | null) | undefined, recibo_bancario?: (string | Array<{[key: string]: string}> | null) | undefined, foto_referencia_catastral?: (string | Array<{[key: string]: string}> | null) | undefined, ultima_factura_de_la_luz?: (string | Array<{[key: string]: string}> | null) | undefined, varios_archivos?: (Array<{[key: string]: string}> | null) | undefined, importe_total?: (number | null) | undefined, forma_de_pago_id?: (number | null) | undefined, cantidad_al_contado?: (number | null) | undefined, cantidad_financiada?: (number | null) | undefined, no_de_cuotas?: (number | null) | undefined, entidad_financiera_firmada?: (string | null) | undefined, puesto_de_trabajo?: (string | null) | undefined, sueldo?: (number | null) | undefined, financiacion_firmada_id?: (number | null) | undefined, promocion_cuota_financiacion_id?: (number | null) | undefined, opciones_pago_al_contado_id?: (number | null) | undefined, opciones_pago_al_contado_tras_previsualizar_id?: (number | null) | undefined, observaciones?: (string | null) | undefined, fecha_preferente_de_montaje?: (string | null) | undefined, estructura_adicional_si_no?: (boolean | null) | undefined, protecciones_electricas_id?: (number | null) | undefined, marca_estructura?: (string | null) | undefined, no_de_paneles?: (number | null) | undefined, marca_de_paneles_id?: (number | null) | undefined, marca_panel_id?: (number | null) | undefined, marca_inversor_id?: (number | null) | undefined, marca_bateria_id?: (number | null) | undefined, modelo_bateria_id?: (number | null) | undefined, notas_instalacion?: (string | null) | undefined, backup?: (boolean | null) | undefined, no_baterias?: (number | null) | undefined, tipo_subvencion?: (number | null) | undefined, auditoria_energetica?: (string | null) | undefined, certificado_energetico?: (string | null) | undefined, tipo_de_suelo_id?: (number | null) | undefined, licencia_de_obra_a_cargo_de?: (string | null) | undefined, asesoramiento_tarifas_autoconsumo?: string | undefined}; export type SaveOrderRequest = {client_data: ClientDataForOrder, calculation_data: BudgetCalculationRequest, selected_option?: (number | null) | undefined, order_data?: (OrderDataForHubSpot | null) | undefined, budget_id: number, comercial_id?: (number | null) | undefined, guardar_borrador?: boolean | undefined}; export type CreateApiApiOrderSaveArgs = {body: SaveOrderRequest}; export type CreateApiApiOrderSaveOptions = {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/order/save */ export const createApiApiOrderSave = async (args: CreateApiApiOrderSaveArgs, options: CreateApiApiOrderSaveOptions) => { 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/order/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()) };