import {z} from 'zod' export type ISO4217SupportedCurrency = 'EUR' | 'GBP' | 'USD'; export type GetApiBusinessV2StatementsArgs = {year: Array, currency: ISO4217SupportedCurrency}; export type GetApiBusinessV2StatementsOptions = {baseUrl?: string | undefined, standardAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const month = z.enum(["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]); export const iSO4217SupportedCurrency = z.enum(["EUR", "GBP", "USD"]); export const statement = z.object({year: z.number().int().optional(), month: month.optional(), currency: iSO4217SupportedCurrency.optional(), file_types: z.array(z.string()).optional()}); export const statements = z.object({total: z.number().int().optional(), results: z.array(statement).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 }; /** * Search Statements * * GET /business/v2/statements */ export const getApiBusinessV2Statements = async (args: GetApiBusinessV2StatementsArgs, options?: GetApiBusinessV2StatementsOptions) => { const {baseUrl = "https://api.soldo.com", fetch: fetchFn = fetch, standardAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.year ?? []) query.append("year", String(item)) if (args.currency != null) query.append("currency", String(args.currency)) if (standardAuth !== undefined) headers.set('authorization', `Bearer ${standardAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/business/v2/statements${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(statements, await res.json()) };