import {z} from 'zod' export type Gender = 'diverse' | 'female' | 'male' | 'unknown'; export type PlaceOfBirthRequest = {city: string, country: string}; export type MaritalStatus = 'single' | 'married' | 'unknown'; export type Address = {line_1: string, line_2?: string | undefined, postal_code: string, city: string, country: string}; export type TaxResidency = {country: string, tax_identification_number?: string | undefined}; export type EmploymentStatus = 'apprenticeship' | 'company_owner' | 'employed' | 'managing_director' | 'public_official' | 'retired' | 'self_employed' | 'student' | 'unemployed'; export type AnnualSalary = 'lt_50k_eur' | 'gte_50k_lt_75k_eur' | 'gte_75k_lt_100k_eur' | 'gte_100k_lt_150k_eur' | 'gte_150k_eur'; export type IndustrySector = '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 type Employment = {status: EmploymentStatus, annual_salary: AnnualSalary, sector: IndustrySector}; export type CustomerRequest = {firstname: string, lastname: string, gender?: Gender | undefined, date_of_birth: string, place_of_birth: PlaceOfBirthRequest, nationalities: Array, phone_number: string, email: string, marital_status?: MaritalStatus | undefined, registered_address: Address, tax_residencies: Array, employment: Employment}; export type BusinessCustomerRequest = {type: 'business', id: string}; export type PersonCustomerRequest = {type: 'person', id: string}; export type BrokerAppsApiEndpointsAccountsAgreementAcceptanceRequest = {agreement_id: string, accepted_at: string, legal_representative?: string | undefined}; export type CreateAccountRequest = {customer: CustomerRequest | BusinessCustomerRequest | PersonCustomerRequest, accepted_agreements: Array, declaration_of_acting_on_own_account: boolean, metadata?: {[key: string]: string} | undefined}; export type CreateApiAccountsArgs = {'LMG-Data-Privacy-Access-Principal': string, 'LMG-Data-Privacy-Access-Justification': string, body: CreateAccountRequest}; export type CreateApiAccountsOptions = {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 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 }; /** * Create Account * * POST /accounts */ export const createApiAccounts = async (args: CreateApiAccountsArgs, options?: CreateApiAccountsOptions) => { const {baseUrl = "https://sandbox.api.lemon.markets/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") 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: "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(customerAccountResponse, await res.json()) };