import {z} from 'zod' export type GetApiCustomerInvoicesArgs = {pageSize?: number | undefined, sortOrder?: ('asc' | 'desc') | undefined, pageCursor?: string | undefined, sortField?: ('id' | 'createdAt' | 'dueDate') | undefined, customerId?: number | undefined, jobId?: number | undefined, invoiceNumber?: string | undefined, dueBefore?: string | undefined, dueAfter?: string | undefined, filterDirectDebitStatus?: ('processing' | 'succeeded' | 'failed') | undefined}; export type GetApiCustomerInvoicesOptions = {baseUrl?: string | undefined, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const links = z.object({href: z.string(), rel: z.string(), type: z.enum(["GET", "POST", "PUT", "PATCH"])}); export const customerInvoice = z.object({id: z.number(), jobId: z.number(), customerId: z.number(), attn: z.string().nullable(), title: z.string(), description: z.string().nullable(), invoiceNumber: z.string().nullable(), receiverEmail: z.string().nullable(), receiverFullName: z.string().nullable(), receiverPostalAddress: z.string().nullable(), dueDate: z.string().nullable(), dueDays: z.union([z.number(), z.string()]).nullable(), invoiceDate: z.string().nullable(), paidAt: z.string().nullable(), subtotal: z.number(), taxValue: z.number(), totalPaid: z.number().nullable(), taxRate: z.number(), type: z.union([z.literal("approved"), z.literal("toBeApproved"), z.literal("draft")]), status: z.union([z.literal("unpaid"), z.literal("draft"), z.literal("voided"), z.literal("paidDisputed"), z.literal("unpaidDisputed"), z.literal("paid")]), isSent: z.boolean(), isFinal: z.boolean(), createdAt: z.string(), fergusPayEnabled: z.boolean(), directDebitStatus: z.union([z.literal("processing"), z.literal("succeeded"), z.literal("failed")]).nullable(), links: z.array(links)}); export const pagination = z.object({perPage: z.number(), pageCount: z.number(), links: z.object({self: z.string(), previous: z.string().nullable(), next: z.string().nullable()})}); export const listCustomerInvoicesResponse = z.object({result: z.string(), data: z.array(customerInvoice), paging: 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 }; /** * Returns a list of invoices. The list can be filtered by customer, job, invoice number, and due dates. * * GET /customerInvoices * * Also accepts auth: PersonalAccessToken */ export const getApiCustomerInvoices = async (args: GetApiCustomerInvoicesArgs, options?: GetApiCustomerInvoicesOptions) => { const {baseUrl = "https://api.fergus.com", fetch: fetchFn = fetch, oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (args.sortOrder != null) query.append("sortOrder", String(args.sortOrder)) if (args.pageCursor != null) query.append("pageCursor", String(args.pageCursor)) if (args.sortField != null) query.append("sortField", String(args.sortField)) if (args.customerId != null) query.append("customerId", String(args.customerId)) if (args.jobId != null) query.append("jobId", String(args.jobId)) if (args.invoiceNumber != null) query.append("invoiceNumber", String(args.invoiceNumber)) if (args.dueBefore != null) query.append("dueBefore", String(args.dueBefore)) if (args.dueAfter != null) query.append("dueAfter", String(args.dueAfter)) if (args.filterDirectDebitStatus != null) query.append("filterDirectDebitStatus", String(args.filterDirectDebitStatus)) if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/customerInvoices${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(listCustomerInvoicesResponse, await res.json()) };