import {z} from 'zod' export type CurrencyCode = string; export type RoundedMonetaryAmount = {amount: string, currency: CurrencyCode}; export type CreditMemoApplicationRequest = {invoice_id: string, amount: RoundedMonetaryAmount, application_date: string}; export type ApplyCreditMemoRequest = {applications: Array}; export type CreateApiCreditMemosCreditMemoIdApplicationsArgs = {credit_memo_id: string, body: ApplyCreditMemoRequest}; export type CreateApiCreditMemosCreditMemoIdApplicationsOptions = {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 fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const creditMemoItem = z.object({id: z.string(), description: z.string(), revenue: itemRevenue, total_amount: roundedMonetaryAmount, taxed_amount: roundedMonetaryAmount.optional(), net_amount: roundedMonetaryAmount, quantity: z.string(), product_id: z.string(), 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 creditMemoApplication = z.object({id: z.string(), credit_memo_id: z.string(), invoice_id: z.string(), invoice_number: z.string().optional(), amount: roundedMonetaryAmount, application_date: z.string()}); export const exchangeRate = z.object({base: currencyCode, target: currencyCode, rate: z.string(), date: z.string()}); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const creditMemo = z.object({id: z.string(), subsidiary_id: z.string(), credit_memo_number: z.string(), customer_id: z.string(), items: z.array(creditMemoItem), credit_memo_date: z.string(), address: address, status: z.enum(["UNAPPLIED", "PARTIALLY_APPLIED", "APPLIED", "REFUNDED"]), net_amount: roundedMonetaryAmount, total: roundedMonetaryAmount, applied_amount: roundedMonetaryAmount, remaining_amount: roundedMonetaryAmount, applications: z.array(creditMemoApplication), exchange_rate: exchangeRate.optional(), taxed_amount: roundedMonetaryAmount, external_references: z.array(externalReference).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 }; /** * Reconciles credit memo applications * * POST /credit-memos/{credit_memo_id}/applications */ export const createApiCreditMemosCreditMemoIdApplications = async (args: CreateApiCreditMemosCreditMemoIdApplicationsArgs, options?: CreateApiCreditMemosCreditMemoIdApplicationsOptions) => { 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(/\/+$/, '')}/credit-memos/${encodeURIComponent(String(args.credit_memo_id))}/applications${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(creditMemo, await res.json()) };