import {z} from 'zod' export type GetApiCnabArgs = {'q[accountNumberEq]='?: string | undefined, 'q[documentNumberEq]='?: number | undefined, 'q[accountTypeEq]='?: ('company' | 'linked' | 'linked_flex') | undefined, 'q[dateEq]'?: string | undefined, 'q[createdAtGt]='?: string | undefined, 'q[createdAtLt]='?: string | undefined, 'p[page]'?: number | undefined, 'p[per_page]'?: number | undefined}; export type GetApiCnabOptions = {baseUrl?: string | undefined, sec0?: {username: string, password: string} | undefined, sec1?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiCnabResponse = z.object({data: z.array(z.object({fileId: z.number().int().optional(), file: z.string().optional(), date: z.string().optional(), accountNumber: z.string().optional(), documentNumber: z.string().optional(), accountName: z.string().optional(), accountType: z.string().optional()})).optional(), pagination: z.object({total_pages: z.number().int().optional(), current_page: z.number().int().optional(), items_per_page: z.number().int().optional(), count: z.number().int().optional(), total_count: z.number().int().optional()}).optional(), success: z.boolean().optional(), message: z.string().optional(), searched: z.object({createdAtGtEq: z.string().optional(), createdAtLtEq: z.string().optional()}).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 }; /** * Baixar arquivos de retorno - CNAB400 * * GET /cnab */ export const getApiCnab = async (args: GetApiCnabArgs, options?: GetApiCnabOptions) => { const {baseUrl = "https://pagamentos.grafeno.be/api/v2", fetch: fetchFn = fetch, sec0, sec1} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['q[accountNumberEq]='] != null) query.append("q[accountNumberEq]=", String(args['q[accountNumberEq]='])) if (args['q[documentNumberEq]='] != null) query.append("q[documentNumberEq]=", String(args['q[documentNumberEq]='])) if (args['q[accountTypeEq]='] != null) query.append("q[accountTypeEq]=", String(args['q[accountTypeEq]='])) if (args['q[dateEq]'] != null) query.append("q[dateEq]", String(args['q[dateEq]'])) if (args['q[createdAtGt]='] != null) query.append("q[createdAtGt]=", String(args['q[createdAtGt]='])) if (args['q[createdAtLt]='] != null) query.append("q[createdAtLt]=", String(args['q[createdAtLt]='])) if (args['p[page]'] != null) query.append("p[page]", String(args['p[page]'])) if (args['p[per_page]'] != null) query.append("p[per_page]", String(args['p[per_page]'])) if (sec0 !== undefined) headers.set('authorization', `Basic ${btoa(`${sec0.username}:${sec0.password}`)}`) if (sec1 !== undefined) headers.set("Authorization", sec1) const url = `${baseUrl.replace(/\/+$/, '')}/cnab${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(getApiCnabResponse, await res.json()) };