import {z} from 'zod' export type GetApiOrganisationsVatVrnLiabilitiesArgs = {vrn: string, from: string, to: string, 'Gov-Test-Scenario'?: string | undefined}; export type GetApiOrganisationsVatVrnLiabilitiesOptions = {baseUrl?: string | undefined, userRestricted?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiOrganisationsVatVrnLiabilitiesResponse = z.object({liabilities: z.array(z.object({taxPeriod: z.object({from: z.string(), to: z.string()}).optional(), type: z.string(), originalAmount: z.number().gte(-9999999999999.99).lte(9999999999999.99).multipleOf(0.01), outstandingAmount: z.number().gte(-9999999999999.99).lte(9999999999999.99).multipleOf(0.01).optional(), due: z.string().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 }; /** * Retrieve VAT liabilities * * GET /organisations/vat/{vrn}/liabilities */ export const getApiOrganisationsVatVrnLiabilities = async (args: GetApiOrganisationsVatVrnLiabilitiesArgs, options?: GetApiOrganisationsVatVrnLiabilitiesOptions) => { const {baseUrl = "https://test-api.service.hmrc.gov.uk", fetch: fetchFn = fetch, userRestricted} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args['Gov-Test-Scenario'] != null) headers.set("Gov-Test-Scenario", String(args['Gov-Test-Scenario'])) if (userRestricted !== undefined) headers.set('authorization', `Bearer ${userRestricted}`) const url = `${baseUrl.replace(/\/+$/, '')}/organisations/vat/${encodeURIComponent(String(args.vrn))}/liabilities${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(getApiOrganisationsVatVrnLiabilitiesResponse, await res.json()) };