import {z} from 'zod' export type CreateInvoiceInput = {sender: {legal_name: string, country_code: string, address_line1: string, address_line2?: string | undefined, postcode: string, city: string, tax_id?: (string | null) | undefined, contact_email: string, contact_phone?: (string | null) | undefined, contact_name?: (string | null) | undefined, tax_registration_id?: (string | null) | undefined}, recipient: {legal_name: string, country_code: string, address_line1: string, address_line2?: string | undefined, postcode: string, city: string, tax_id?: (string | null) | undefined, contact_email: string, leitweg_id?: (string | null) | undefined}, line_items: Array<{description: string, quantity: string, unit_code?: (string | null) | undefined, unit_price: string, tax_rate: string, tax_category_code: 'S' | 'Z' | 'E' | 'AE' | 'K' | 'G' | 'O', discount?: ({type: 'amount', value: string, reason: string} | {type: 'percent', value: string, reason: string}) | undefined, tax_exemption_code?: (string | null) | undefined, tax_exemption_reason?: (string | null) | undefined}>, currency: string, jurisdiction?: (string | null) | undefined, format_override?: ('zugferd_comfort' | 'zugferd_basic' | 'xrechnung_cii' | 'xrechnung_ubl' | 'plain_pdf') | undefined, notes?: string | undefined, invoice_number?: (string | null) | undefined, issue_date?: string | undefined, due_date?: string | undefined, payment_terms?: (string | null) | undefined, payment_means?: ({type: 'credit_transfer', iban?: (string | null) | undefined, bic?: (string | null) | undefined, account_number?: (string | null) | undefined, routing_number?: (string | null) | undefined, account_name?: (string | null) | undefined, bank?: (string | null) | undefined}) | undefined, delivery_date?: string | undefined, delivery_period?: {start: string, end: string} | undefined}; export type CreateApiApiV1InvoicesArgs = {'Idempotency-Key'?: string | undefined, 'X-Email-Verification-Token'?: string | undefined, body: CreateInvoiceInput}; export type CreateApiApiV1InvoicesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const invoice = z.object({invoice_id: z.string(), document_id: z.string(), format: z.enum(["zugferd_comfort", "zugferd_basic", "xrechnung_cii", "xrechnung_ubl", "plain_pdf"]), download_url: z.string(), download_url_expires_at: z.string(), preview_url: z.string().optional(), preview_url_expires_at: z.string().optional(), submission: z.object({status: z.literal("not_provided"), message: z.string(), manual_upload_hints: z.array(z.object({label: z.string(), url: z.string(), leitweg_prefix: z.string().optional()})).optional(), planned: z.array(z.string()).optional()}).optional(), validator_summary: z.object({valid: z.boolean(), validator: z.string(), errors: z.array(z.object({path: z.string().optional(), rule: z.string().optional(), message: z.string()})).optional()}), magic_link_sent: z.boolean(), recipient_email_sent: z.boolean().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 }; /** * Generate a compliant e-invoice * * POST /api/v1/invoices */ export const createApiApiV1Invoices = async (args: CreateApiApiV1InvoicesArgs, options?: CreateApiApiV1InvoicesOptions) => { const {baseUrl = "https://scribo.causaprima.ai", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args['X-Email-Verification-Token'] != null) headers.set("X-Email-Verification-Token", String(args['X-Email-Verification-Token'])) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/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(invoice, await res.json()) };