import {z} from 'zod' export type CurrencyCode = string; export type MonetaryAmount = {amount: string, currency: CurrencyCode}; export type CreditMemoItemPriceRequest = {product_id: string, quantity: number, 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 RoundedMonetaryAmount = {amount: string, currency: CurrencyCode}; 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 CreateCreditMemoItemRequest = {description: string, price: CreditMemoItemPriceRequest, revenue?: ItemRevenue | undefined, tax_rate?: TaxRateWithOptionalAmountAndCode | 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 CreateCreditMemoRequest = {credit_memo_number?: string | undefined, customer_id: string, subsidiary_id?: string | undefined, credit_memo_date: string, items: Array, external_references?: Array | undefined, exchange_rate?: ExchangeRate | undefined}; export type CreateApiCreditMemosArgs = {body: CreateCreditMemoRequest}; export type CreateApiCreditMemosOptions = {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 }; /** * Creates a credit memo * * POST /credit-memos */ export const createApiCreditMemos = async (args: CreateApiCreditMemosArgs, options?: CreateApiCreditMemosOptions) => { 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${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()) };