import {z} from 'zod' export type PageLimit = number; export type PageCursor = string; export type GetApiDraftContractsArgs = {limit?: PageLimit | undefined, cursor?: PageCursor | undefined, subsidiary_id?: string | undefined, customer_id?: string | undefined}; export type GetApiDraftContractsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const currencyCode = z.string(); export const monetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const contractScope = z.enum(["FULL", "REVENUE_RECOGNITION_ONLY"]); export const fixedRecurringPrice = z.object({amount: monetaryAmount, interval_months: z.number().int().gte(1).lte(12), type: z.string()}); export const oneTimePrice = z.object({amount: monetaryAmount, type: z.string()}); export const perUnitBilling = z.object({type: z.string(), amount: monetaryAmount, units: z.number().int().gte(1)}); export const tier = z.object({up_to: z.number().int().gte(1), flat_price: monetaryAmount.optional(), per_unit_price: monetaryAmount.optional()}); export const tieredBilling = z.object({type: z.string(), mode: z.enum(["GRADUATED", "METERED"]), tiers: z.array(tier)}); export const billingScheme = z.discriminatedUnion("type", [perUnitBilling, tieredBilling]); export const usagePrice = z.object({interval_months: z.number().int().gte(1).lte(12), type: z.string(), billing_scheme: billingScheme}); export const price = z.discriminatedUnion("type", [fixedRecurringPrice, oneTimePrice, usagePrice]); export const roundedMonetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const amountDiscount = z.object({amount_off: roundedMonetaryAmount, type: z.string().optional()}); export const percentageDiscount = z.object({percentage_off: z.number().gte(0).lte(100), type: z.string().optional()}); export const discount = z.discriminatedUnion("type", [amountDiscount, percentageDiscount]); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const draftContractItem = z.object({id: z.string(), product_id: z.string(), price: price, quantity: z.string(), discount: discount.optional(), start_date: z.string().optional(), end_date: z.string().optional(), description: z.string().optional(), fields: fieldAssignments.optional(), declared_ssp: monetaryAmount.nullable().optional()}); export const countryCode = z.string(); 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 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 contractApproval = z.object({approval_request_id: z.string(), operation: z.enum(["CREATE", "UPDATE"]), status: z.enum(["WAITING", "APPROVED", "REJECTED", "CANCELLED", "WITHDRAWN"]), reason: z.string().nullable().optional()}); export const draftContract = z.object({id: z.string(), external_references: z.array(externalReference), subsidiary_id: z.string(), customer_id: z.string(), name: z.string(), amount: monetaryAmount, close_date: z.string(), start_date: z.string().optional(), end_date: z.string().optional(), scope: contractScope.nullable().optional(), items: z.array(draftContractItem), purchase_order_number: z.string().optional(), shipping_customer_id: z.string().nullable().optional(), billing_address: customerAddress.nullable().optional(), shipping_address: customerAddress.nullable().optional(), email_selection: emailSelection.nullable().optional(), approval: contractApproval.nullable().optional()}); export const pageCursor = z.string(); export const pagination = z.object({next_cursor: pageCursor.optional()}); export const getApiDraftContractsResponse = z.object({draft_contracts: z.array(draftContract), pagination: pagination.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 }; /** * Lists all draft contracts * * GET /draft-contracts */ export const getApiDraftContracts = async (args: GetApiDraftContractsArgs, options?: GetApiDraftContractsOptions) => { const {baseUrl = "https://api.rillet.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.subsidiary_id != null) query.append("subsidiary_id", String(args.subsidiary_id)) if (args.customer_id != null) query.append("customer_id", String(args.customer_id)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/draft-contracts${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiDraftContractsResponse, await res.json()) };