import {z} from 'zod' export type GetApiOrganisationsVatVrnInformationArgs = {vrn: string, 'Gov-Test-Scenario'?: string | undefined}; export type GetApiOrganisationsVatVrnInformationOptions = {baseUrl?: string | undefined, userRestricted?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiOrganisationsVatVrnInformationResponse = z.object({customerDetails: z.object({effectiveRegistrationDate: z.string().optional()}).optional(), flatRateScheme: z.object({frsCategory: z.enum(["001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "013", "014", "015", "016", "017", "018", "019", "020", "021", "022", "023", "024", "025", "026", "027", "028", "029", "030", "031", "032", "033", "034", "035", "036", "037", "038", "039", "040", "041", "042", "043", "044", "045", "046", "047", "048", "049", "050", "051", "052", "053", "054", "055", "999"]).optional(), startDate: 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 }; /** * Retrieve VAT customer information * * GET /organisations/vat/{vrn}/information */ export const getApiOrganisationsVatVrnInformation = async (args: GetApiOrganisationsVatVrnInformationArgs, options?: GetApiOrganisationsVatVrnInformationOptions) => { 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['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))}/information${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(getApiOrganisationsVatVrnInformationResponse, await res.json()) };