import {z} from 'zod' export type TaxPreviewHumaBody = {disbursementDate: string, finalDueDate: string, grossAmount: string, jurisdictionCode: string, netDeliveredAmount?: string | undefined, taxRegime: string}; export type CreateApiApiV1BrTaxPreviewArgs = {body: TaxPreviewHumaBody}; export type CreateApiApiV1BrTaxPreviewOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const taxPreviewResponse = z.object({cofins: z.string(), grossAmount: z.string(), iofAdditional: z.string(), iofDaily: z.string(), jurisdictionCode: z.string(), netDeliveredAmount: z.string(), pis: z.string(), profileVersion: z.string(), rateTableSnapshotId: z.string(), taxRegime: z.string(), totalIof: z.string(), totalTax: z.string()}); export const taxPreviewEnvelopeResponse = z.object({data: taxPreviewResponse}); 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 }; /** * Preview jurisdiction tax amounts * * POST /api/v1/br/tax/preview */ export const createApiApiV1BrTaxPreview = async (args: CreateApiApiV1BrTaxPreviewArgs, options?: CreateApiApiV1BrTaxPreviewOptions) => { const {baseUrl = "https://identity.sandbox.lerian.net", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/br/tax/preview${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(taxPreviewEnvelopeResponse, await res.json()) };