import {z} from 'zod' export type GetApiBooksRulesArgs = {booksId?: string | undefined, pageToken?: string | undefined, limit?: number | undefined}; export type GetApiBooksRulesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const booksAPICategorizationRuleAmountCondition = z.object({amount: z.number(), operator: z.enum(["lessThan", "lessThanOrEqualTo", "greaterThan", "greaterThanOrEqualTo", "equalTo"])}); export const booksAPICategorizationRuleDescriptionCondition = z.object({contains: z.string()}); export const booksAPICategorizationRuleCounterpartyCondition = z.object({name: z.string()}); export const booksAPICategorizationRuleDebitCardCondition = z.object({debitCardId: z.string()}); export const booksAPICategorizationRuleCreditCardCondition = z.object({creditCardId: z.string()}); export const booksAPICategorizationRuleUserCondition = z.object({userId: z.string()}); export const booksAPICategorizationRuleCustomCategoryCondition = z.object({customCategoryId: z.string()}); export const booksAPICategorizationRuleCondition = z.union([z.object({contents: booksAPICategorizationRuleAmountCondition, tag: z.literal("amount")}), z.object({contents: booksAPICategorizationRuleDescriptionCondition, tag: z.literal("description")}), z.object({contents: booksAPICategorizationRuleCounterpartyCondition, tag: z.literal("counterparty")}), z.object({contents: booksAPICategorizationRuleDebitCardCondition, tag: z.literal("debitCard")}), z.object({contents: booksAPICategorizationRuleCreditCardCondition, tag: z.literal("creditCard")}), z.object({contents: booksAPICategorizationRuleUserCondition, tag: z.literal("user")}), z.object({contents: booksAPICategorizationRuleCustomCategoryCondition, tag: z.literal("customCategory")})]); export const booksAPICategorizationRuleSetLedgerOutput = z.object({ledgerId: z.string()}); export const booksAPICategorizationRuleOutput = z.object({contents: booksAPICategorizationRuleSetLedgerOutput, tag: z.literal("setLedger")}); export const booksAPICategorizationRule = z.object({conditions: z.array(booksAPICategorizationRuleCondition), glCodeName: z.string().nullable().optional(), id: z.string(), lastApplied: z.string().nullable().optional(), outputs: z.array(booksAPICategorizationRuleOutput), status: z.enum(["active", "inactive", "invalid"])}); export const getBooksAPICategorizationRulesResponse = z.object({nextPageToken: z.string().nullable().optional(), rules: z.array(booksAPICategorizationRule)}); 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 }; /** * List categorization rules * * GET /books/rules */ export const getApiBooksRules = async (args: GetApiBooksRulesArgs, options?: GetApiBooksRulesOptions) => { const {baseUrl = "https://api.mercury.com/api/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.booksId != null) query.append("booksId", String(args.booksId)) if (args.pageToken != null) query.append("pageToken", String(args.pageToken)) if (args.limit != null) query.append("limit", String(args.limit)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/books/rules${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(getBooksAPICategorizationRulesResponse, await res.json()) };