import {z} from 'zod' export type PageLimit = number; export type PageCursor = string; export type InvoiceStatus = 'UNPAID' | 'PAID' | 'PARTIALLY_PAID' | 'UNBILLED' | 'CREDITED' | 'PARTIALLY_CREDITED'; export type GetApiInvoicesArgs = {limit?: PageLimit | undefined, cursor?: PageCursor | undefined, subsidiary_id?: string | undefined, overdue?: boolean | undefined, customer_id?: string | undefined, external_reference_id?: string | undefined, external_reference_type?: string | undefined, 'updated.gt'?: string | undefined, status?: InvoiceStatus | undefined}; export type GetApiInvoicesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const calendarPeriod = z.object({start: z.string(), end: z.string()}); export const revenuePattern = z.enum(["DAILY", "EVEN_PERIOD", "PROGRESS"]); export const accountCode = z.string(); export const itemRevenue = z.object({period: calendarPeriod.optional(), pattern: revenuePattern.optional(), account_code: accountCode.optional()}); export const currencyCode = z.string(); export const roundedMonetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const invoiceItem = z.object({id: z.string(), description: z.string(), revenue: itemRevenue, total_amount: roundedMonetaryAmount, total_discount: roundedMonetaryAmount, taxed_amount: roundedMonetaryAmount, gross_rate: roundedMonetaryAmount, quantity: z.string(), product_id: z.string(), external_references: z.array(externalReference), fields: fieldAssignments.optional()}); export const countryCode = z.string(); export const address = z.object({line1: z.string(), line2: z.string().nullable().optional(), city: z.string(), state: z.string().nullable().optional(), zip_code: z.string(), country: countryCode}); export const customerAddress = z.object({id: z.string().optional(), line1: z.string(), line2: z.string().nullable().optional(), city: z.string(), state: z.string().nullable().optional(), zip_code: z.string(), country: countryCode}); export const invoicingBankAccount = z.object({id: z.string(), ach_account: z.string(), ach_routing: z.string(), bank_name: z.string(), bank_address: z.string().optional(), swift_code: z.string().optional(), payment_instructions: z.string().optional()}); export const invoiceStatus = z.enum(["UNPAID", "PAID", "PARTIALLY_PAID", "UNBILLED", "CREDITED", "PARTIALLY_CREDITED"]); export const exchangeRate = z.object({base: currencyCode, target: currencyCode, rate: z.string(), date: z.string()}); export const emailSelectionMode = z.enum(["ALL_CUSTOMER_EMAILS", "SELECTED_EMAILS"]); export const emailRecipientType = z.enum(["MAIN_SENDER", "CC", "BCC"]); export const emailRecipient = z.object({customer_email_id: z.string(), recipient_type: emailRecipientType}); export const emailRecipients = z.array(emailRecipient); export const emailSelection = z.object({mode: emailSelectionMode, recipients: emailRecipients.nullable().optional()}); export const invoice = z.object({id: z.string(), subsidiary_id: z.string(), invoice_number: z.string(), customer_id: z.string(), contract_id: z.string().optional(), items: z.array(invoiceItem), due_date: z.string(), invoice_date: z.string(), address: address.optional(), customer_address: customerAddress.optional(), shipping_address: customerAddress.optional(), shipping_customer_id: z.string().nullable().optional(), bank_account: invoicingBankAccount.optional(), status: invoiceStatus, net_amount: roundedMonetaryAmount, amount_due: roundedMonetaryAmount, total: roundedMonetaryAmount, payment_terms: z.number().int().gte(0), subtotal: roundedMonetaryAmount, total_discount: roundedMonetaryAmount, purchase_order_number: z.string().optional(), exchange_rate: exchangeRate.optional(), taxed_amount: roundedMonetaryAmount, memo: z.string().optional(), overdue: z.boolean(), external_references: z.array(externalReference).optional(), metadata: z.record(z.string(), z.string()).optional(), updated_at: z.string(), sent_at: z.string().optional(), email_selection: emailSelection}); export const pageCursor = z.string(); export const pagination = z.object({next_cursor: pageCursor.optional()}); export const getApiInvoicesResponse = z.object({invoices: z.array(invoice), pagination: pagination.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 }; /** * Lists all invoices * * GET /invoices */ export const getApiInvoices = async (args: GetApiInvoicesArgs, options?: GetApiInvoicesOptions) => { 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.overdue != null) query.append("overdue", String(args.overdue)) if (args.customer_id != null) query.append("customer_id", String(args.customer_id)) if (args.external_reference_id != null) query.append("external_reference_id", String(args.external_reference_id)) if (args.external_reference_type != null) query.append("external_reference_type", String(args.external_reference_type)) if (args['updated.gt'] != null) query.append("updated.gt", String(args['updated.gt'])) if (args.status != null) query.append("status", String(args.status)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/invoices${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(getApiInvoicesResponse, await res.json()) };