import {z} from 'zod' export type AccountCode = string; export type CurrencyCode = string; export type RoundedMonetaryAmount = {amount: string, currency: CurrencyCode}; export type CountryCode = string; export type ExpenseTaxRate = {percentage: unknown, tax_amount: RoundedMonetaryAmount, country: CountryCode, type: 'VAT' | 'SALES_TAX', description: string, tax_code?: string | undefined, coverage: 'INCLUSIVE' | 'EXCLUSIVE'}; export type CalendarPeriod = {start: string, end: string}; export type FieldAssignments = Array<{field_id: string, field_value_id: string}>; export type CreateReimbursementItemRequest = {description?: string | undefined, account_code: AccountCode, amount: RoundedMonetaryAmount, tax_rate?: ExpenseTaxRate | undefined, service_period?: CalendarPeriod | undefined, fields?: FieldAssignments | undefined}; export type ExternalReference = {type: string, id: string, url?: string | undefined}; export type ExchangeRate = {base: CurrencyCode, target: CurrencyCode, rate: string, date: string}; export type CreateReimbursementRequest = {vendor_id: string, items: Array, reimbursement_date: string, payable_account_code: AccountCode, impact_date?: string | undefined, subsidiary_id?: string | undefined, external_references?: Array | undefined, exchange_rate?: ExchangeRate | undefined}; export type CreateApiReimbursementsArgs = {body: CreateReimbursementRequest}; export type CreateApiReimbursementsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const accountCode = z.string(); export const currencyCode = z.string(); export const roundedMonetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const countryCode = z.string(); export const expenseTaxRate = z.object({percentage: z.string(), tax_amount: roundedMonetaryAmount, country: countryCode, type: z.enum(["VAT", "SALES_TAX"]), description: z.string(), tax_code: z.string().optional(), coverage: z.enum(["INCLUSIVE", "EXCLUSIVE"])}); export const calendarPeriod = z.object({start: z.string(), end: z.string()}); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const exchangeRate = z.object({base: currencyCode, target: currencyCode, rate: z.string(), date: z.string()}); export const reimbursementStatus = z.enum(["DRAFT", "UNPAID", "PAID", "PARTIALLY_PAID"]); export const pendingApprovalRequest = z.object({id: z.string(), workflow_id: z.string(), operation: z.enum(["CREATE", "UPDATE", "DELETE"]), status: z.literal("PENDING")}); export const reimbursement = z.object({vendor_id: z.string(), items: z.array(z.object({description: z.string().optional(), account_code: accountCode, amount: roundedMonetaryAmount, tax_rate: expenseTaxRate.optional(), service_period: calendarPeriod.optional(), fields: fieldAssignments.optional(), id: z.string()})), reimbursement_date: z.string().optional(), impact_date: z.string().optional(), subsidiary_id: z.string().optional(), external_references: z.array(externalReference).optional(), exchange_rate: exchangeRate.optional(), id: z.string(), status: reimbursementStatus, pending_approval_request: pendingApprovalRequest.nullable().optional(), updated_at: 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 a reimbursement * * POST /reimbursements */ export const createApiReimbursements = async (args: CreateApiReimbursementsArgs, options?: CreateApiReimbursementsOptions) => { 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(/\/+$/, '')}/reimbursements${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(reimbursement, await res.json()) };