import {z} from 'zod' export type Client = {buildingNumber?: string | undefined, ccEmails?: Array | undefined, city?: string | undefined, country?: string | undefined, details?: string | undefined, email?: string | undefined, files?: (Array<{digest: string, name: string, path: string, size: number, type?: 'CloudFile' | undefined, uploadDate?: (string | null) | undefined, url?: (string | null) | undefined}>) | undefined, id?: string | undefined, invoiceEmailSubjects?: {[key: string]: string} | undefined, name: string, notes?: string | undefined, street?: string | undefined, zip?: string | undefined}; export type Invoice = {bankId?: (string | null) | undefined, clientId?: string | undefined, clientRef?: string | undefined, confirmDate?: boolean | undefined, currency?: string | undefined, date?: string | undefined, description?: string | undefined, disableRounding?: boolean | undefined, exchangeRate?: (number | null) | undefined, generationCount?: number | undefined, headerDescription?: string | undefined, hideQuotePricing?: boolean | undefined, id?: string | undefined, isArchived?: boolean | undefined, isPaid?: boolean | undefined, items?: (Array<{catalogItemId?: (string | null) | undefined, details?: ({date: string, from: string, to: string, type: 'HourlyRateDetails'} | null) | undefined, discount?: number | undefined, id?: (string | null) | undefined, isCreditNoteItem?: boolean | undefined, name: string, price?: number | undefined, unitBasis?: ({type: 'preset' | 'custom', value: string} | null) | undefined, units?: number | undefined, usageCount?: number | undefined, vatRate?: number | undefined}>) | undefined, language?: ('de' | 'en' | 'fr' | 'it') | undefined, payments?: ({items?: (Array<{amount: number, date?: string | undefined, id?: (string | null) | undefined, methodId: string}>) | undefined, proof?: ({digest: string, name: string, path: string, size: number, type?: 'CloudFile' | undefined, uploadDate?: (string | null) | undefined, url?: (string | null) | undefined} | null) | undefined}) | undefined, recurring?: ('disabled' | 'monthly' | 'quarterly' | 'yearly' | 'biYearly' | 'triYearly') | undefined, recurringAutoSend?: boolean | undefined, recurringDueDate?: (string | null) | undefined, sent?: boolean | undefined, sentEmailHistory?: (Array<{ccEmails?: Array | undefined, date: string, email: string, invoiceStatus?: ('quote' | 'invoice' | 'reminder' | 'confirmation' | 'orderConfirmation' | 'deliveryBill' | 'advancePayment') | undefined, isTest: boolean, note?: (string | null) | undefined, success: boolean}>) | undefined, type?: ('normal' | 'quote') | undefined, vatEnabled?: boolean | undefined, vatMode?: ('additive' | 'inclusive') | undefined, version?: number | undefined}; export type CreateInvoiceRequest = {client?: Client | undefined, clientId?: string | undefined, confirmDate?: boolean | undefined, invoice: Invoice}; export type CreateApiInvoicesCreateArgs = {body: CreateInvoiceRequest}; export type CreateApiInvoicesCreateOptions = {baseUrl: string, ApiKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const successEnvelope = z.object({data: z.unknown(), success: z.literal(true)}); 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 an invoice draft * * POST /invoices/create * * Also accepts auth: FirebaseIdToken */ export const createApiInvoicesCreate = async (args: CreateApiInvoicesCreateArgs, options: CreateApiInvoicesCreateOptions) => { 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 (ApiKeyHeader !== undefined) headers.set("X-API-Key", ApiKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/invoices/create${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(successEnvelope, await res.json()) };