import {z} from 'zod' export type CurrencyCode = string; export type RoundedMonetaryAmount = {amount: string, currency: CurrencyCode}; export type AmountDiscount = {amount_off: RoundedMonetaryAmount, type?: string | undefined}; export type PercentageDiscount = {percentage_off: number, type?: string | undefined}; export type Discount = AmountDiscount | PercentageDiscount; export type MonetaryAmount = {amount: string, currency: CurrencyCode}; export type InvoiceItemPriceRequest = {product_id: string, quantity: number, discount?: Discount | undefined, amount_per_unit: MonetaryAmount}; export type CalendarPeriod = {start: string, end: string}; export type RevenuePattern = 'DAILY' | 'EVEN_PERIOD' | 'PROGRESS'; export type AccountCode = string; export type ItemRevenue = {period?: CalendarPeriod | undefined, pattern?: RevenuePattern | undefined, account_code?: AccountCode | undefined}; export type CountryCode = string; export type TaxRateWithOptionalAmountAndCode = {percentage: unknown, tax_amount?: RoundedMonetaryAmount | undefined, country: CountryCode, type: 'VAT' | 'SALES_TAX', description: string}; export type FieldAssignments = Array<{field_id: string, field_value_id: string}>; export type CreateFullInvoiceItemRequest = {description: string, price: InvoiceItemPriceRequest, revenue?: ItemRevenue | undefined, tax_rate?: TaxRateWithOptionalAmountAndCode | undefined, fields?: FieldAssignments | undefined}; export type NullableId = string | null; export type EmailSelectionMode = 'ALL_CUSTOMER_EMAILS' | 'SELECTED_EMAILS'; export type EmailRecipientType = 'MAIN_SENDER' | 'CC' | 'BCC'; export type EmailRecipient = {customer_email_id: string, recipient_type: EmailRecipientType}; export type EmailRecipients = Array; export type EmailSelection = {mode: EmailSelectionMode, recipients?: (EmailRecipients | null) | undefined}; export type ExternalReference = {type: string, id: string, url?: string | undefined}; export type InlineMetadataValues = {[key: string]: string | null}; export type UpdateRevenueRecognitionOnlyInvoiceItemRequest = {id: string, description?: string | undefined, revenue?: ItemRevenue | undefined, fields?: FieldAssignments | undefined}; export type ExchangeRate = {base: CurrencyCode, target: CurrencyCode, rate: string, date: string}; export type UpdateInvoiceRequest = {items: Array, due_date?: string | undefined, invoice_date: string, purchase_order_number?: string | undefined, memo?: string | undefined, bank_account_id: string, shipping_customer_id?: NullableId | undefined, billing_address_id?: NullableId | undefined, shipping_address_id?: NullableId | undefined, email_selection?: EmailSelection | undefined, external_references?: Array | undefined, metadata?: (InlineMetadataValues | null) | undefined, scope?: string | undefined} | {invoice_date: string, due_date?: string | undefined, invoice_number?: string | undefined, items: Array, external_references?: Array | undefined, exchange_rate?: ExchangeRate | undefined, metadata?: (InlineMetadataValues | null) | undefined, scope?: string | undefined}; export type UpdateApiInvoicesInvoiceIdArgs = {invoice_id: string, body: UpdateInvoiceRequest}; export type UpdateApiInvoicesInvoiceIdOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const calendarPeriod = z.object({start: z.string(), end: z.string()}); export const revenuePattern = z.enum(["DAILY", "EVEN_PERIOD", "PROGRESS"]); export const accountCode = z.string(); export const itemRevenue = z.object({period: calendarPeriod.optional(), pattern: revenuePattern.optional(), account_code: accountCode.optional()}); export const currencyCode = z.string(); export const roundedMonetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const invoiceItem = z.object({id: z.string(), description: z.string(), revenue: itemRevenue, total_amount: roundedMonetaryAmount, total_discount: roundedMonetaryAmount, taxed_amount: roundedMonetaryAmount, gross_rate: roundedMonetaryAmount, quantity: z.string(), product_id: z.string(), external_references: z.array(externalReference), fields: fieldAssignments.optional()}); export const countryCode = z.string(); export const address = z.object({line1: z.string(), line2: z.string().nullable().optional(), city: z.string(), state: z.string().nullable().optional(), zip_code: z.string(), country: countryCode}); export const customerAddress = z.object({id: z.string().optional(), line1: z.string(), line2: z.string().nullable().optional(), city: z.string(), state: z.string().nullable().optional(), zip_code: z.string(), country: countryCode}); export const invoicingBankAccount = z.object({id: z.string(), ach_account: z.string(), ach_routing: z.string(), bank_name: z.string(), bank_address: z.string().optional(), swift_code: z.string().optional(), payment_instructions: z.string().optional()}); export const invoiceStatus = z.enum(["UNPAID", "PAID", "PARTIALLY_PAID", "UNBILLED", "CREDITED", "PARTIALLY_CREDITED"]); export const exchangeRate = z.object({base: currencyCode, target: currencyCode, rate: z.string(), date: z.string()}); export const emailSelectionMode = z.enum(["ALL_CUSTOMER_EMAILS", "SELECTED_EMAILS"]); export const emailRecipientType = z.enum(["MAIN_SENDER", "CC", "BCC"]); export const emailRecipient = z.object({customer_email_id: z.string(), recipient_type: emailRecipientType}); export const emailRecipients = z.array(emailRecipient); export const emailSelection = z.object({mode: emailSelectionMode, recipients: emailRecipients.nullable().optional()}); export const invoice = z.object({id: z.string(), subsidiary_id: z.string(), invoice_number: z.string(), customer_id: z.string(), contract_id: z.string().optional(), items: z.array(invoiceItem), due_date: z.string(), invoice_date: z.string(), address: address.optional(), customer_address: customerAddress.optional(), shipping_address: customerAddress.optional(), shipping_customer_id: z.string().nullable().optional(), bank_account: invoicingBankAccount.optional(), status: invoiceStatus, net_amount: roundedMonetaryAmount, amount_due: roundedMonetaryAmount, total: roundedMonetaryAmount, payment_terms: z.number().int().gte(0), subtotal: roundedMonetaryAmount, total_discount: roundedMonetaryAmount, purchase_order_number: z.string().optional(), exchange_rate: exchangeRate.optional(), taxed_amount: roundedMonetaryAmount, memo: z.string().optional(), overdue: z.boolean(), external_references: z.array(externalReference).optional(), metadata: z.record(z.string(), z.string()).optional(), updated_at: z.string(), sent_at: z.string().optional(), email_selection: emailSelection}); 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 }; /** * Updates an invoice * * PUT /invoices/{invoice_id} */ export const updateApiInvoicesInvoiceId = async (args: UpdateApiInvoicesInvoiceIdArgs, options?: UpdateApiInvoicesInvoiceIdOptions) => { const {baseUrl = "https://api.rillet.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/invoices/${encodeURIComponent(String(args.invoice_id))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", 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()) };