import {z} from 'zod' export type LinkRequest = string; export type AttachPdf = boolean; export type SaveData = boolean; export type DateFrom = string; export type DateTo = string; export type TaxReturnsMonthlyRequest = {link: LinkRequest, attach_pdf?: AttachPdf | undefined, save_data?: SaveData | undefined, type: string, date_from: DateFrom, date_to: DateTo}; export type TaxReturnsYearlyRequest = {link: LinkRequest, attach_pdf?: AttachPdf | undefined, save_data?: SaveData | undefined, type: string, year_from: string, year_to: string}; export type CreateApiApiTaxReturnsArgs = {omit?: string | undefined, fields?: string | undefined, body: TaxReturnsMonthlyRequest | TaxReturnsYearlyRequest}; export type CreateApiApiTaxReturnsOptions = {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 collectedAt = z.string(); export const createdAt = z.string(); export const taxReturnPersonal = z.object({id: id.optional(), link: link.optional(), collected_at: collectedAt, created_at: createdAt.optional(), informacion_general: z.object({}).nullable(), sueldos_salarios: z.object({}).nullable(), servicios_profesionales: z.object({}).nullable(), deducciones_personales: z.object({}).nullable(), determinacion_impuesto: z.object({}).nullable(), retenciones: z.object({}).nullable(), dividendos: z.object({}).nullable(), datos_informativos: z.object({}).nullable().optional(), pdf: z.string().nullable(), receipt_pdf: z.string().nullable()}).and(z.record(z.string(), z.unknown())); export const taxReturnPersonalMonthly = z.object({id: id.optional(), collected_at: collectedAt, created_at: createdAt.optional(), informacion_general: z.object({}).nullable(), isr: z.object({}).nullable(), iva: z.object({}).nullable(), pdf: z.string().nullable(), receipt_pdf: z.string().nullable().optional(), type: z.string()}).and(z.record(z.string(), z.unknown())); export const taxReturnBusiness = z.object({id: id, collected_at: collectedAt, created_at: createdAt, informacion_general: z.object({}).nullable(), datos_adicionales: z.object({}).nullable(), estado_resultados: z.object({}).nullable(), estado_posicion_financiera_balance: z.object({}).nullable(), conciliacion_entre_resultado_contable_fiscal: z.object({}).nullable(), deducciones_autorizadas: z.object({}).nullable(), cifras_cierre_ejercicio: z.object({}).nullable(), determinacion_del_impuesto_sobre_la_renta: z.object({}).nullable(), dividendos_o_utilidades_distribuidos: z.object({}).nullable(), detalle_pago_r1_isr_personas_morales: z.object({}).nullable(), ingressos: z.object({}).nullable().optional(), determinacion: z.object({}).nullable().optional(), pdf: z.string().nullable(), receipt_pdf: z.string().nullable()}).and(z.record(z.string(), z.unknown())); export const taxReturnBusinessMonthly = z.object({id: id.optional(), collected_at: collectedAt, created_at: createdAt.optional(), informacion_general: z.object({}).nullable(), determinacion_isr: z.object({}).nullable(), detalle_pago_isr: z.object({}).nullable(), determinacion_iva: z.object({}).nullable(), detalle_pago_iva: z.object({}).nullable(), pdf: z.string().nullable(), receipt_pdf: z.string().nullable().optional(), type: z.string().nullable()}).and(z.record(z.string(), z.unknown())); export const createApiApiTaxReturnsResponse = z.array(z.union([taxReturnPersonal, taxReturnPersonalMonthly, taxReturnBusiness, taxReturnBusinessMonthly])); 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 tax returns for a link * * POST /api/tax-returns/ */ export const createApiApiTaxReturns = async (args: CreateApiApiTaxReturnsArgs, options?: CreateApiApiTaxReturnsOptions) => { 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/tax-returns/${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(createApiApiTaxReturnsResponse, await res.json()) };