import {z} from 'zod' export type BooksAPICategorizationRuleAmountCondition = {amount: number, operator: 'lessThan' | 'lessThanOrEqualTo' | 'greaterThan' | 'greaterThanOrEqualTo' | 'equalTo'}; export type BooksAPICategorizationRuleDescriptionCondition = {contains: string}; export type BooksAPICategorizationRuleCounterpartyCondition = {name: string}; export type BooksAPICategorizationRuleDebitCardCondition = {debitCardId: string}; export type BooksAPICategorizationRuleCreditCardCondition = {creditCardId: string}; export type BooksAPICategorizationRuleUserCondition = {userId: string}; export type BooksAPICategorizationRuleCustomCategoryCondition = {customCategoryId: string}; export type BooksAPICategorizationRuleCondition = {contents: BooksAPICategorizationRuleAmountCondition, tag: 'amount'} | {contents: BooksAPICategorizationRuleDescriptionCondition, tag: 'description'} | {contents: BooksAPICategorizationRuleCounterpartyCondition, tag: 'counterparty'} | {contents: BooksAPICategorizationRuleDebitCardCondition, tag: 'debitCard'} | {contents: BooksAPICategorizationRuleCreditCardCondition, tag: 'creditCard'} | {contents: BooksAPICategorizationRuleUserCondition, tag: 'user'} | {contents: BooksAPICategorizationRuleCustomCategoryCondition, tag: 'customCategory'}; export type BooksAPICategorizationRuleSetLedgerOutput = {ledgerId: unknown}; export type BooksAPICategorizationRuleOutput = {contents: BooksAPICategorizationRuleSetLedgerOutput, tag: 'setLedger'}; export type CreateBooksAPICategorizationRuleRequest = {conditions: Array, outputs: Array}; export type CreateApiBooksRulesArgs = {booksId?: string | undefined, body: CreateBooksAPICategorizationRuleRequest}; export type CreateApiBooksRulesOptions = {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 createBooksAPICategorizationRuleResponse = z.object({rule: 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 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 }; /** * Create a categorization rule * * POST /books/rules */ export const createApiBooksRules = async (args: CreateApiBooksRulesArgs, options?: CreateApiBooksRulesOptions) => { const {baseUrl = "https://api.mercury.com/api/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.booksId != null) query.append("booksId", String(args.booksId)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/books/rules${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(createBooksAPICategorizationRuleResponse, await res.json()) };