import {z} from 'zod' export type CreateApiV1EstimationsArgs = {body: {energyTypes: Array<'ELECTRICITY' | 'GAS'>, familySize: '1' | '2' | '3' | '4' | '>5', hasHeatPump?: boolean | undefined, evCount?: number | undefined, solarPanelCount?: number | undefined, hasBattery?: boolean | undefined}}; export type CreateApiV1EstimationsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const electricityConsumptionProfile = z.object({consumptionTotalKwh: z.number(), consumptionDayKwh: z.number().nullable(), consumptionNightKwh: z.number().nullable(), injectionTotalKwh: z.number().nullable(), injectionDayKwh: z.number().nullable(), injectionNightKwh: z.number().nullable(), peakConsumptionKw: z.number().nullable(), inverterCapacityKva: z.number().nullable()}); export const gasConsumptionProfile = z.object({consumptionTotalKwh: z.number()}); export const estimationResult = z.object({electricity: electricityConsumptionProfile.optional(), gas: gasConsumptionProfile.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 }; /** * Estimate a Consumption Profile from an Energy Profile * * POST /v1/estimations */ export const createApiV1Estimations = async (args: CreateApiV1EstimationsArgs, options?: CreateApiV1EstimationsOptions) => { const {baseUrl = "https://open-energie.api.vwala.be", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/estimations${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(estimationResult, await res.json()) };