import {z} from 'zod' export type ExternalReference = {type: string, id: string, url?: string | undefined}; export type CurrencyCode = string; export type MonetaryAmount = {amount: string, currency: CurrencyCode}; export type ContractScope = 'FULL' | 'REVENUE_RECOGNITION_ONLY'; export type FixedRecurringPrice = {amount: MonetaryAmount, interval_months: number, type: string}; export type OneTimePrice = {amount: MonetaryAmount, type: string}; export type PerUnitBilling = {type: string, amount: MonetaryAmount, units: number}; export type Tier = {up_to: number, flat_price?: MonetaryAmount | undefined, per_unit_price?: MonetaryAmount | undefined}; export type TieredBilling = {type: string, mode: 'GRADUATED' | 'METERED', tiers: Array}; export type BillingScheme = PerUnitBilling | TieredBilling; export type UsagePrice = {interval_months: number, type: string, billing_scheme: BillingScheme}; export type Price = FixedRecurringPrice | OneTimePrice | UsagePrice; 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 FieldAssignments = Array<{field_id: string, field_value_id: string}>; export type DraftContractItemRequest = {product_id: string, price: Price, quantity: number, discount?: Discount | undefined, start_date?: string | undefined, end_date?: string | undefined, description?: string | undefined, fields?: FieldAssignments | undefined, declared_ssp?: (MonetaryAmount | null) | 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 CreateDraftContractRequest = {external_references?: Array | undefined, subsidiary_id: string, customer_id: string, name: string, amount: MonetaryAmount, close_date: string, start_date?: string | undefined, end_date?: string | undefined, scope: ContractScope, items: Array, purchase_order_number?: string | undefined, shipping_customer_id?: NullableId | undefined, billing_address_id?: NullableId | undefined, shipping_address_id?: NullableId | undefined, email_selection?: EmailSelection | undefined}; export type CreateApiDraftContractsArgs = {body: CreateDraftContractRequest}; export type CreateApiDraftContractsOptions = {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 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 draft contract * * POST /draft-contracts */ export const createApiDraftContracts = async (args: CreateApiDraftContractsArgs, options?: CreateApiDraftContractsOptions) => { 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(/\/+$/, '')}/draft-contracts${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(draftContract, await res.json()) };