import {z} from 'zod' export type InvoiceLineInput = {description: string, quantity?: (number | string) | undefined, unit?: (string | null) | undefined, unit_price?: (number | string) | undefined, tax_rate?: (number | string | null) | undefined, product_id?: (string | null) | undefined, price_id?: (string | null) | undefined, fiscal_refs?: ({[key: string]: string} | null) | undefined}; export type ScheduleCreate = {name: string, payee_id?: (string | null) | undefined, frequency: 'weekly' | 'biweekly' | 'monthly' | 'quarterly' | 'semiannual' | 'yearly', start_date?: (string | null) | undefined, end_type?: ('never' | 'on_date' | 'after_count') | undefined, end_date?: (string | null) | undefined, end_count?: (number | null) | undefined, payment_terms_days?: (number | null) | undefined, currency?: (string | null) | undefined, notes?: (string | null) | undefined, custom_fields?: ({[key: string]: unknown} | null) | undefined, lines: Array, discount?: (number | string | null) | undefined, origin?: ('local' | 'imported' | null) | undefined, external_source?: (string | null) | undefined, external_id?: (string | null) | undefined}; export type CreateApiApiInvoiceSchedulesArgs = {'X-Workspace-Id'?: (string | null) | undefined, body: ScheduleCreate}; export type CreateApiApiInvoiceSchedulesOptions = {baseUrl: string, OAuth2PasswordBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const invoicePayee = z.object({id: z.string(), name: z.string()}); export const scheduleTermRead = z.object({id: z.string(), effective_from: z.string(), lines: z.array(z.record(z.string(), z.unknown())), discount: z.string(), subtotal: z.string(), tax_total: z.string(), total: z.string(), created_at: z.string()}); export const scheduleRead = z.object({id: z.string(), name: z.string(), payee_id: z.string().nullable(), payee: invoicePayee.nullable().optional(), origin: z.string(), external_source: z.string().nullable().optional(), external_id: z.string().nullable().optional(), status: z.enum(["active", "paused", "ended"]), pause_reason: z.enum(["manual", "failures"]).nullable().optional(), ended_at: z.string().nullable().optional(), end_reason: z.enum(["canceled_by_client", "canceled_by_us", "completed", "unpaid", "other"]).nullable().optional(), frequency: z.enum(["weekly", "biweekly", "monthly", "quarterly", "semiannual", "yearly"]), start_date: z.string(), end_type: z.enum(["never", "on_date", "after_count"]), end_date: z.string().nullable().optional(), end_count: z.number().int().nullable().optional(), payment_terms_days: z.number().int().nullable().optional(), currency: z.string(), notes: z.string().nullable().optional(), custom_fields: z.record(z.string(), z.unknown()).nullable().optional(), next_sequence: z.number().int(), last_generated_at: z.string().nullable().optional(), consecutive_failures: z.number().int(), terms: z.array(scheduleTermRead).optional(), created_at: z.string(), current_term: scheduleTermRead.nullable().optional(), next_term: scheduleTermRead.nullable().optional(), monthly_amount: z.string().optional(), next_period_start: z.string().nullable().optional(), invoice_count: z.number().int().optional(), amount_invoiced: z.string().optional(), amount_paid: z.string().optional(), past_due_count: z.number().int().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 }; /** * Create Schedule * * POST /api/invoice-schedules */ export const createApiApiInvoiceSchedules = async (args: CreateApiApiInvoiceSchedulesArgs, options: CreateApiApiInvoiceSchedulesOptions) => { const {baseUrl, fetch: fetchFn = fetch, OAuth2PasswordBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Workspace-Id'] != null) headers.set("X-Workspace-Id", String(args['X-Workspace-Id'])) if (OAuth2PasswordBearer !== undefined) headers.set('authorization', `Bearer ${OAuth2PasswordBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/invoice-schedules${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(scheduleRead, await res.json()) };