import {z} from 'zod' export type CreateApiV1CheckoutArgs = {body: {locale?: ('nl' | 'fr') | undefined, selection: Array<{energyType: 'ELECTRICITY' | 'GAS', productVersionId: string}>, context: {meterType?: ('Digital' | 'Analog' | null) | undefined, currentMerchants?: ({electricity?: (string | null) | undefined, gas?: (string | null) | undefined}) | undefined}, intake: {supplyPoint: {postalCode: string, city: string, residential?: boolean | undefined, meterType?: ('Digital' | 'Analog' | null) | undefined, tariffType?: ('enkelvoudig' | 'tweevoudig' | 'nachtmeter' | null) | undefined, hasExclusiveNightRegister?: boolean | undefined}, consumption?: ({electricity?: ({consumptionTotalKwh: number, consumptionDayKwh?: (number | null) | undefined, consumptionNightKwh?: (number | null) | undefined, injectionTotalKwh?: (number | null) | undefined, injectionDayKwh?: (number | null) | undefined, injectionNightKwh?: (number | null) | undefined, peakConsumptionKw?: (number | null) | undefined, consumptionExclusiveNightKwh?: (number | null) | undefined} | null) | undefined, gas?: ({consumptionTotalKwh: number} | null) | undefined}) | undefined, referenceCost?: ({electricity?: ({yearlyInclVat?: (number | null) | undefined, currentMerchant?: (string | null) | undefined, currentProduct?: (string | null) | undefined} | null) | undefined, gas?: ({yearlyInclVat?: (number | null) | undefined, currentMerchant?: (string | null) | undefined, currentProduct?: (string | null) | undefined} | null) | undefined}) | undefined}, customer: {firstName: string, lastName: string, email: string, mobilePhone: string, address: string, iban: string}, eans?: ({electricity?: (string | null) | undefined, gas?: (string | null) | undefined}) | undefined, paymentMethod: 'DIRECT_DEBIT' | 'BANK_TRANSFER', billingPreference: 'ADVANCE_INVOICE' | 'MONTHLY_SETTLEMENT', contractStartDate: string | string, consentGiven: true, consentGivenAt: string | string}}; export type CreateApiV1CheckoutOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const submittedCheckout = z.object({checkoutId: z.string(), boltHandoffAuthorized: z.boolean(), submissionIds: z.array(z.string()), submissionMethods: z.array(z.object({energyType: z.enum(["ELECTRICITY", "GAS"]), submissionMethod: z.enum(["MANUAL", "REDIRECT", "INTEGRATION"]), urlHandoffAuthorized: z.boolean()}))}); 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 }; /** * Submit a selection Vwala will switch on the customer's behalf * * POST /v1/checkout */ export const createApiV1Checkout = async (args: CreateApiV1CheckoutArgs, options?: CreateApiV1CheckoutOptions) => { 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/checkout${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(submittedCheckout, await res.json()) };