import {z} from 'zod' export type Address = {addressLine1: string, addressLine2?: string | undefined, city: string, zipCode: string, state?: string | undefined, country: string}; export type ClientDetails = {contactId?: string | undefined, billingName: string, contactName?: string | undefined, phone?: string | undefined, email: string, address?: (string | Address) | undefined}; export type PaymentTerms = {name: string, description?: string | undefined, days: number, paymentDueDate?: string | undefined, discount?: number | undefined, penalty?: number | undefined}; export type LineItem = {name: string, description?: string | undefined, price: number, taxRate?: number | undefined, taxable?: boolean | undefined, metadata?: Record | undefined, inventoryId?: string | undefined, quantity?: number | undefined, total: number, serviceDate?: string | undefined, tags?: Array | undefined}; export type Frequency = 'Weekly' | 'Bi-Weekly' | 'Monthly' | 'Bi-Monthly' | 'Quarterly'; export type AppInvoicesApiInvoicesSchemaInvoiceStatus = 'draft' | 'issued' | 'paid' | 'partially paid' | 'overdue' | 'expired' | 'cancelled' | 'archived' | 'uncollectible'; export type Invoice = {createdByUserId?: string | undefined, dateIssued: string, invoiceNumber: number, clientDetails: ClientDetails, paymentTerms?: Array | undefined, paymentInstructions?: Record | undefined, billingPeriodStart?: string | undefined, billingPeriodEnd?: string | undefined, lineItems: Array, taxRate: number, totalTax: number, subTotal: number, totalDue: number, paymentDueDate: string, totalDiscount?: number | undefined, depositAmount?: number | undefined, depositDate?: string | undefined, parentProjectId?: string | undefined, recurringFrequency?: Frequency | undefined, status?: AppInvoicesApiInvoicesSchemaInvoiceStatus | undefined, metadata?: Record | undefined}; export type CreateApiInvoicesArgs = {'x-business-id': string, body: Invoice}; export type CreateApiInvoicesOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const invoiceID = z.object({invoiceId: z.string()}); 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 Invoice * * POST /invoices * * Also accepts auth: AccessToken */ export const createApiInvoices = async (args: CreateApiInvoicesArgs, options: CreateApiInvoicesOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-business-id'] != null) headers.set("x-business-id", String(args['x-business-id'])) if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/invoices${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(invoiceID, await res.json()) };