import {z} from 'zod' export type ExternalId = string; export type GetApiReceivablesArgs = {limit?: number | undefined, page?: string | undefined, expand?: Array<'total_count'> | undefined, sort?: 'created_at_desc' | undefined, creditor_id?: ExternalId | undefined, obligor_id?: ExternalId | undefined, metadata?: {[key: string]: unknown} | undefined, debt_line_id?: string | undefined, funded_by?: ('sivo' | 'balance_sheet' | 'other') | undefined, outstanding?: (boolean | string) | undefined, eligibility?: ('eligible' | 'ineligible' | 'obligor_type' | 'country' | 'currency' | 'product_type' | 'term_length' | 'credit_limit' | 'max_balance' | 'apr' | 'review') | undefined}; export type GetApiReceivablesOptions = {baseUrl?: string | undefined, APIKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const cfdi = z.string(); export const nfe = z.string(); export const peppol = z.string(); export const getApiReceivablesResponse = z.object({data: z.array(z.object({obligor_id: z.string().min(1).max(255), origination_date: z.string(), currency: z.string(), product_type: z.enum(["term_loan", "line_of_credit", "buy_now_pay_later", "credit_card", "invoice", "earned_wage_access", "lease", "gig_payout", "creator_payout", "merchant_payout", "rental_payout", "marketplace_payout", "real_estate_commission", "subscription", "government_salary", "government_contract", "bank_transfer", "stock_sell_settlement"]), funded_by: z.enum(["sivo", "balance_sheet", "other"]), delinquent_amount: z.number().int().gte(0), delinquent_times: z.number().int().gte(0).lte(2147483647), creditor_id: z.string().min(1).max(255).optional(), origination_fee: z.number().int().gte(0).optional(), periodic_fee: z.object({cycle_type: z.string(), amount: z.number().int().gte(0)}).optional(), collateral: z.enum(["cash", "vehicle", "equipment", "all_business_assets", "receivables", "residential_property", "commercial_property", "other"]).optional(), term: z.string().optional(), interest_rate: z.number().gte(-10).lte(10).optional(), credit_limit: z.number().int().gte(0).optional(), payment_frequency: z.string().optional(), metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]).nullable()).optional(), fund_name: z.string().min(1).optional(), delinquent_since: z.string().optional(), fiscal_id: z.union([cfdi, nfe, peppol]).optional(), id: z.string().min(1).max(255), created_at: z.string(), created_by: z.string(), updated_at: z.string(), updated_by: z.string()})), has_more: z.boolean(), next_page: z.string().min(1).max(1024).nullable(), previous_page: z.string().min(1).max(1024).nullable(), total_count: z.number().int().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 }; /** * List all receivables * * GET /receivables * * Also accepts auth: OAuth2 */ export const getApiReceivables = async (args: GetApiReceivablesArgs, options?: GetApiReceivablesOptions) => { const {baseUrl = "https://core.sivo.com", fetch: fetchFn = fetch, APIKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.page != null) query.append("page", String(args.page)) for (const item of args.expand ?? []) query.append("expand", String(item)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.creditor_id != null) query.append("creditor_id", String(args.creditor_id)) if (args.obligor_id != null) query.append("obligor_id", String(args.obligor_id)) if (args.metadata != null) query.append("metadata", JSON.stringify(args.metadata)) if (args.debt_line_id != null) query.append("debt_line_id", String(args.debt_line_id)) if (args.funded_by != null) query.append("funded_by", String(args.funded_by)) if (args.outstanding != null) query.append("outstanding", String(args.outstanding)) if (args.eligibility != null) query.append("eligibility", String(args.eligibility)) if (APIKeyAuth !== undefined) headers.set("Authorization", APIKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/receivables${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(getApiReceivablesResponse, await res.json()) };