import {z} from 'zod' export type LinkRequest = string; export type EnumInvoiceAllowedIncomeTypesRequest = 'SALARY' | 'GOVERNMENT' | 'INTEREST' | 'RENT' | 'RETIREMENT' | 'FREELANCE' | 'ALTERNATIVE_INCOME' | 'TRANSFER' | 'DEPOSIT' | 'UNKNOWN'; export type EnumIncomeMinimumConfidenceLevelRequest = 'HIGH' | 'MEDIUM' | 'LOW'; export type DateFrom = string; export type DateTo = string; export type Token = string; export type SaveData = boolean; export type CreateApiApiIncomesArgs = {omit?: string | undefined, fields?: string | undefined, body: {link: LinkRequest, allowed_income_types?: Array | undefined, minimum_confidence_level?: EnumIncomeMinimumConfidenceLevelRequest | undefined, date_from?: DateFrom | undefined, date_to?: DateTo | undefined, token?: Token | undefined, save_data?: SaveData | undefined}}; export type CreateApiApiIncomesOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const id = z.string(); export const link = z.string().nullable(); export const createdAt = z.string(); export const enumIncomeStreamType = z.enum(["SALARY", "GOVERNMENT", "INTEREST", "RENT", "RETIREMENT", "FREELANCE", "ALTERNATIVE_INCOME", "TRANSFER", "DEPOSIT", "UNKNOWN"]); export const enumIncomeStreamFrequency = z.enum(["MONTHLY", "FORTNIGHTLY", "WEEKLY", "IRREGULAR", "SINGLE"]); export const enumIncomeStreamConfidence = z.enum(["HIGH", "MEDIUM", "LOW"]); export const incomeStreamsBody = z.object({account_id: z.string(), income_type: enumIncomeStreamType, frequency: enumIncomeStreamFrequency, monthly_average: z.number(), monthly_median: z.number().optional(), average_income_amount: z.number(), last_income_amount: z.number(), currency: z.string(), last_income_description: z.string(), last_income_date: z.string(), stability: z.number().nullable(), regularity: z.number().nullable(), trend: z.number().nullable(), lookback_periods: z.number().int(), full_periods: z.number().int(), periods_with_income: z.number().int(), number_of_incomes: z.number().int(), confidence: enumIncomeStreamConfidence}); export const enumIncomeSourceType = z.literal("BANK"); export const income = z.object({id: id, link: link, created_at: createdAt, income_streams: z.array(incomeStreamsBody), income_source_type: enumIncomeSourceType, first_transaction_date: z.string().nullable(), last_transaction_date: z.string(), best_working_day_to_charge: z.number().int(), good_working_days_to_charge: z.array(z.number().int()), number_of_income_streams: z.number().int(), monthly_average: z.number(), monthly_average_regular: z.number(), monthly_average_irregular: z.number(), monthly_average_low_confidence: z.number(), monthly_average_medium_confidence: z.number(), monthly_average_high_confidence: z.number(), total_income_amount: z.number(), total_regular_income_amount: z.number(), total_irregular_income_amount: z.number().optional(), total_low_confidence: z.number(), total_medium_confidence: z.number(), total_high_confidence: z.number()}); 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 }; /** * Retrieve incomes for a link * * POST /api/incomes/ */ export const createApiApiIncomes = async (args: CreateApiApiIncomesArgs, options?: CreateApiApiIncomesOptions) => { const {baseUrl = "https://sandbox.belvo.com", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.omit != null) query.append("omit", String(args.omit)) if (args.fields != null) query.append("fields", String(args.fields)) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/incomes/${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(income, await res.json()) };