import {z} from 'zod' export type PageLimit = number; export type PageCursor = string; export type BillStatusFilter = 'UNPAID' | 'PAID' | 'PARTIALLY_PAID' | 'CREDITED' | 'PARTIALLY_CREDITED' | 'APPLIED'; export type GetApiBillsArgs = {limit?: PageLimit | undefined, cursor?: PageCursor | undefined, subsidiary_id?: string | undefined, 'updated.gt'?: string | undefined, vendor_id?: string | undefined, status?: BillStatusFilter | undefined}; export type GetApiBillsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const accountCode = z.string(); export const currencyCode = z.string(); export const roundedMonetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const countryCode = z.string(); export const expenseTaxRate = z.object({percentage: z.string(), tax_amount: roundedMonetaryAmount, country: countryCode, type: z.enum(["VAT", "SALES_TAX"]), description: z.string(), tax_code: z.string().optional(), coverage: z.enum(["INCLUSIVE", "EXCLUSIVE"])}); export const calendarPeriod = z.object({start: z.string(), end: z.string()}); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const exchangeRate = z.object({base: currencyCode, target: currencyCode, rate: z.string(), date: z.string()}); export const billStatus = z.enum(["DRAFT", "UNPAID", "PAID", "PARTIALLY_PAID", "CREDITED", "PARTIALLY_CREDITED", "APPLIED"]); export const pendingApprovalRequest = z.object({id: z.string(), workflow_id: z.string(), operation: z.enum(["CREATE", "UPDATE", "DELETE"]), status: z.literal("PENDING")}); export const bill = z.object({vendor_id: z.string(), expense_number: z.string(), items: z.array(z.object({description: z.string().optional(), account_code: accountCode, amount: roundedMonetaryAmount, tax_rate: expenseTaxRate.optional(), service_period: calendarPeriod.optional(), fields: fieldAssignments.optional(), id: z.string()})), bill_date: z.string(), due_date: z.string(), impact_date: z.string().optional(), subsidiary_id: z.string().optional(), external_references: z.array(externalReference).optional(), exchange_rate: exchangeRate.optional(), metadata: z.record(z.string(), z.string().nullable()).optional(), id: z.string(), status: billStatus, pending_approval_request: pendingApprovalRequest.nullable().optional(), updated_at: z.string()}); export const pageCursor = z.string(); export const pagination = z.object({next_cursor: pageCursor.optional()}); export const getApiBillsResponse = z.object({bills: z.array(bill), pagination: pagination}); 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 }; /** * Lists all bills * * GET /bills */ export const getApiBills = async (args: GetApiBillsArgs, options?: GetApiBillsOptions) => { const {baseUrl = "https://api.rillet.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.subsidiary_id != null) query.append("subsidiary_id", String(args.subsidiary_id)) if (args['updated.gt'] != null) query.append("updated.gt", String(args['updated.gt'])) if (args.vendor_id != null) query.append("vendor_id", String(args.vendor_id)) if (args.status != null) query.append("status", String(args.status)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/bills${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(getApiBillsResponse, await res.json()) };