import {z} from 'zod' export type CustomerAccountStatus = 'closed' | 'created' | 'opened' | 'rejected'; export type GetApiAccountsArgs = {cursor?: string | undefined, limit?: number | undefined, status?: CustomerAccountStatus | undefined, person_customer?: boolean | undefined, 'LMG-Data-Privacy-Access-Principal': string, 'LMG-Data-Privacy-Access-Justification': string}; export type GetApiAccountsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const bankAccountResponse = z.object({iban: z.string(), bic: z.string(), name: z.string().optional()}); export const gender = z.enum(["diverse", "female", "male", "unknown"]); export const placeOfBirthRequest = z.object({city: z.string().max(255), country: z.string().min(2).max(2)}); export const maritalStatus = z.enum(["single", "married", "unknown"]); export const address = z.object({line_1: z.string().max(128), line_2: z.string().max(128).optional(), postal_code: z.string().max(50), city: z.string().max(150), country: z.string().min(2).max(2)}); export const taxResidency = z.object({country: z.string().min(2).max(2), tax_identification_number: z.string().min(1).max(255).optional()}); export const employmentStatus = z.enum(["apprenticeship", "company_owner", "employed", "managing_director", "public_official", "retired", "self_employed", "student", "unemployed"]); export const annualSalary = z.enum(["lt_50k_eur", "gte_50k_lt_75k_eur", "gte_75k_lt_100k_eur", "gte_100k_lt_150k_eur", "gte_150k_eur"]); export const industrySector = z.enum(["agriculture", "commodities", "construction", "education", "financial_services", "gambling", "healthcare", "it", "jewellery_trading", "manufacturing", "precious_metals_trading", "professional_services", "public_sector", "real_estate", "retail", "service_industry", "sport", "tourism", "transport", "used_vehicles_trading", "weapons_trading", "other"]); export const employment = z.object({status: employmentStatus, annual_salary: annualSalary, sector: industrySector}); export const customerResponse = z.object({id: z.string().optional(), firstname: z.string(), lastname: z.string(), gender: gender.optional(), date_of_birth: z.string(), place_of_birth: placeOfBirthRequest, nationalities: z.array(z.string().min(2).max(2)), phone_number: z.string(), email: z.string(), marital_status: maritalStatus.optional(), registered_address: address, tax_residencies: z.array(taxResidency), employment: employment}); export const personCustomerResponse = z.object({type: z.literal("person"), id: z.string(), person: z.string()}); export const businessCustomerResponse = z.object({type: z.literal("business"), id: z.string(), business: z.string()}); export const customerAccountStatus = z.enum(["closed", "created", "opened", "rejected"]); export const statusChangeCustomerAccountStatus = z.object({status: customerAccountStatus, timestamp: z.string()}); export const brokerAppsApiEndpointsAccountsSecuritiesAccountResponse = z.object({number: z.string()}); export const acceptedAgreementResponse = z.object({agreement: z.string(), accepted_at: z.string(), person: z.string()}); export const customerAccountResponse = z.object({id: z.string(), cash_account: bankAccountResponse.optional(), customer: z.union([customerResponse, personCustomerResponse, businessCustomerResponse]), declaration_of_acting_on_own_account: z.boolean(), history: z.array(statusChangeCustomerAccountStatus), reference_account: bankAccountResponse.optional(), securities_account: brokerAppsApiEndpointsAccountsSecuritiesAccountResponse.optional(), status: customerAccountStatus, metadata: z.record(z.string(), z.string()).optional(), agreements: z.array(acceptedAgreementResponse).optional()}); export const pagination = z.object({next_cursor: z.string().optional()}); export const pageCustomerAccountResponse = z.object({data: z.array(customerAccountResponse), pagination: pagination}); 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 }; /** * List Accounts * * GET /accounts */ export const getApiAccounts = async (args: GetApiAccountsArgs, options?: GetApiAccountsOptions) => { const {baseUrl = "https://sandbox.api.lemon.markets/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.status != null) query.append("status", String(args.status)) if (args.person_customer != null) query.append("person_customer", String(args.person_customer)) if (args['LMG-Data-Privacy-Access-Principal'] != null) headers.set("LMG-Data-Privacy-Access-Principal", String(args['LMG-Data-Privacy-Access-Principal'])) if (args['LMG-Data-Privacy-Access-Justification'] != null) headers.set("LMG-Data-Privacy-Access-Justification", String(args['LMG-Data-Privacy-Access-Justification'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/accounts${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(pageCustomerAccountResponse, await res.json()) };