import {z} from 'zod' export type CurrencyCode = string; export type MonetaryAmount = {amount: string, currency: CurrencyCode}; 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 RevenuePattern = 'DAILY' | 'EVEN_PERIOD' | 'PROGRESS'; export type ProgressMeasure = 'MILESTONES'; export type MilestoneValueMode = 'PERCENTAGE' | 'AMOUNT'; export type RoundedMonetaryAmount = {amount: string, currency: CurrencyCode}; export type ContractMilestoneRequest = {key: string, name: string, sequence: number, percentage?: string | undefined, amount?: RoundedMonetaryAmount | undefined, expected_date?: (string | null) | undefined}; export type ProgressPlanRequest = {measure: ProgressMeasure, value_mode: MilestoneValueMode, milestones: Array}; 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 CountryCode = string; export type TaxRateWithOptionalAmount = {percentage: unknown, tax_amount?: RoundedMonetaryAmount | undefined, country: CountryCode, type: 'VAT' | 'SALES_TAX', description: string}; export type ExternalReference = {type: string, id: string, url?: string | undefined}; export type FieldAssignments = Array<{field_id: string, field_value_id: string}>; export type AccountCode = string; export type UsageCommitment = {amount: RoundedMonetaryAmount, revenue_account: AccountCode}; export type ContractItemRequest = {id?: string | undefined, product_id: string, price: Price, quantity: number, revenue_pattern?: RevenuePattern | undefined, progress_plan?: ProgressPlanRequest | undefined, discount?: Discount | undefined, tax_rate?: TaxRateWithOptionalAmount | undefined, start_date?: string | undefined, end_date?: string | undefined, external_reference?: ExternalReference | undefined, fields?: FieldAssignments | undefined, usage_minimum_commitment?: UsageCommitment | undefined, description?: string | undefined, declared_ssp?: (MonetaryAmount | null) | undefined}; export type MonthlyInvoicing = {payment_terms: number, interval: string, day: number}; export type MonthlyProratedInvoicing = {payment_terms: number, interval: string, day: number}; export type QuarterlyInvoicing = {payment_terms: number, interval: string, month_day: string}; export type SemiAnnualInvoicing = {payment_terms: number, interval: string, month_day: string}; export type YearlyInvoicing = {payment_terms: number, interval: string, month_day: string}; export type Invoicing = MonthlyInvoicing | MonthlyProratedInvoicing | QuarterlyInvoicing | SemiAnnualInvoicing | YearlyInvoicing; export type UsageInvoicingFrequency = 'MONTHLY' | 'QUARTERLY' | 'SEMI_ANNUAL' | 'YEARLY'; export type PaymentTerms = number; export type UsageInvoiceDate = 'FIRST_DAY_OF_NEXT_CYCLE' | 'LAST_DAY_OF_CURRENT_CYCLE'; export type UsageInvoiceCycle = 'CALENDAR' | 'SUBSCRIPTION_ANNIVERSARY'; export type UsageInvoicing = {frequency: UsageInvoicingFrequency, payment_terms: PaymentTerms, invoice_date: UsageInvoiceDate, cycle: UsageInvoiceCycle}; export type MinimumCommitmentInvoicingFrequency = 'MONTHLY' | 'MONTHLY_PRORATED' | 'QUARTERLY' | 'SEMI_ANNUAL' | 'YEARLY'; export type MinimumCommitmentInvoicing = {frequency: MinimumCommitmentInvoicingFrequency, payment_terms: PaymentTerms}; export type UsageConfiguration = {usage_invoicing: UsageInvoicing, minimum_commitment_invoicing?: MinimumCommitmentInvoicing | undefined, minimum_commitment_cycle?: ('MONTHLY' | 'CONTRACT') | undefined, contract_level_minimum_commitment?: UsageCommitment | 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 ExchangeRate = {base: CurrencyCode, target: CurrencyCode, rate: string, date: string}; export type BillingPeriod = {start: string, end: string}; export type ContractInvoiceScheduleItem = {contract_item_id?: string | undefined, description: string, quantity: string, price_type: 'FIXED' | 'USAGE' | 'USAGE_COMMITMENT', unit_amount: RoundedMonetaryAmount, total_amount: RoundedMonetaryAmount, billing_period: BillingPeriod}; export type ContractInvoiceScheduleEntry = {issue_date: string, currency: string, total: RoundedMonetaryAmount, items: Array}; export type ContractInvoiceSchedule = {invoices: Array}; export type ContractScope = 'FULL' | 'REVENUE_RECOGNITION_ONLY'; export type RevenueRecognitionOnlyContractItemRequest = {product_id: string, price: MonetaryAmount, discount?: Discount | undefined, revenue_pattern: RevenuePattern, start_date?: string | undefined, end_date?: string | undefined, external_reference: ExternalReference, declared_ssp?: (MonetaryAmount | null) | undefined}; export type InvoiceScheduleInvoiceItem = {description: string, contract_item_reference: string, quantity: unknown, total_amount: RoundedMonetaryAmount, tax_amount?: RoundedMonetaryAmount | undefined, discount_amount?: RoundedMonetaryAmount | undefined, external_references: Array}; export type InvoiceScheduleInvoice = {due_date?: string | undefined, invoice_date: string, invoice_number: string, tax_amount?: RoundedMonetaryAmount | undefined, items: Array, external_references: Array}; export type InvoiceSchedule = {invoices?: Array | undefined}; export type CreateContractRequest = {name: string, close_date: string, start_date: string, end_date?: string | undefined, items: Array, invoicing?: Invoicing | undefined, usage_configuration?: UsageConfiguration | undefined, external_references?: Array | undefined, customer_id: string, subsidiary_id?: string | undefined, shipping_customer_id?: string | undefined, billing_address_id?: NullableId | undefined, shipping_address_id?: NullableId | undefined, email_selection?: EmailSelection | undefined, exchange_rate?: ExchangeRate | undefined, purchase_order_number?: string | undefined, invoice_schedule?: ContractInvoiceSchedule | undefined, scope: ContractScope} | {name: string, close_date?: string | undefined, start_date: string, end_date?: string | undefined, items: Array, invoice_schedule: InvoiceSchedule, external_references: Array, customer_id: string, subsidiary_id?: string | undefined, scope: ContractScope}; export type CreateApiContractsArgs = {idempotency_key?: string | undefined, body: CreateContractRequest}; export type CreateApiContractsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const productType = z.enum(["PRODUCT", "BUNDLE"]); export const currencyCode = z.string(); export const monetaryAmount = z.object({amount: z.string(), currency: currencyCode}); 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 revenuePattern = z.enum(["DAILY", "EVEN_PERIOD", "PROGRESS"]); export const progressMeasure = z.literal("MILESTONES"); export const milestoneValueMode = z.enum(["PERCENTAGE", "AMOUNT"]); export const contractMilestoneStatus = z.enum(["OPEN", "DUE_THIS_PERIOD", "OVERDUE", "COMPLETED", "CANCELLED"]); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const contractMilestoneCancellation = z.object({effective_date: z.string(), credit_memo_id: z.string().nullable().optional()}); export const contractMilestone = z.object({id: z.string(), key: z.string(), name: z.string(), sequence: z.number().int(), percentage: z.string().nullable().optional(), allocated_amount: roundedMonetaryAmount.nullable().optional(), amount: roundedMonetaryAmount.nullable().optional(), expected_date: z.string().nullable().optional(), status: contractMilestoneStatus, completed_date: z.string().nullable().optional(), memo: z.string().nullable().optional(), external_references: z.array(externalReference), cancellation: contractMilestoneCancellation.nullable().optional()}); export const progressPlan = z.object({measure: progressMeasure, value_mode: milestoneValueMode, as_of_date: z.string(), milestones: z.array(contractMilestone)}); 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 countryCode = z.string(); export const taxRate = z.object({percentage: z.string(), tax_amount: roundedMonetaryAmount.optional(), country: countryCode, type: z.enum(["VAT", "SALES_TAX"]), description: z.string()}); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const accountCode = z.string(); export const usageCommitment = z.object({amount: roundedMonetaryAmount, revenue_account: accountCode}); export const bundleInvoiceDisplay = z.enum(["BUNDLE_AND_COMPONENTS", "BUNDLE_LINE_ONLY"]); export const contractItemBundleComponent = z.object({id: z.string(), product_id: z.string(), product_name: z.string(), quantity: z.string(), revenue_pattern: revenuePattern, allocated_amount: roundedMonetaryAmount}); export const contractItemBundle = z.object({invoice_display: bundleInvoiceDisplay, components: z.array(contractItemBundleComponent)}); export const contractItem = z.object({id: z.string(), product_id: z.string(), product_type: productType, price: price, quantity: z.string(), total_value: roundedMonetaryAmount, revenue_pattern: revenuePattern.optional(), progress_plan: progressPlan.nullable().optional(), discount: discount.optional(), tax_rate: taxRate.optional(), start_date: z.string(), end_date: z.string().optional(), status: z.enum(["AMENDED", "ACTIVE"]), amending: z.string().optional(), fields: fieldAssignments.optional(), external_references: z.array(externalReference), usage_minimum_commitment: usageCommitment.optional(), description: z.string().optional(), bundle: contractItemBundle.optional(), declared_ssp: monetaryAmount.nullable().optional()}); export const contractStatus = z.enum(["ACTIVE", "IN_EFFECT", "CANCELLED", "ENDED", "AMENDED"]); export const monthlyInvoicing = z.object({payment_terms: z.number().int().gte(0), interval: z.string(), day: z.number().int().gte(1).lte(31)}); export const monthlyProratedInvoicing = z.object({payment_terms: z.number().int().gte(0), interval: z.string(), day: z.number().int().gte(1).lte(31)}); export const quarterlyInvoicing = z.object({payment_terms: z.number().int().gte(0), interval: z.string(), month_day: z.string()}); export const semiAnnualInvoicing = z.object({payment_terms: z.number().int().gte(0), interval: z.string(), month_day: z.string()}); export const yearlyInvoicing = z.object({payment_terms: z.number().int().gte(0), interval: z.string(), month_day: z.string()}); export const invoicing = z.discriminatedUnion("interval", [monthlyInvoicing, monthlyProratedInvoicing, quarterlyInvoicing, semiAnnualInvoicing, yearlyInvoicing]); export const usageInvoicingFrequency = z.enum(["MONTHLY", "QUARTERLY", "SEMI_ANNUAL", "YEARLY"]); export const paymentTerms = z.number().int().gte(0); export const usageInvoiceDate = z.enum(["FIRST_DAY_OF_NEXT_CYCLE", "LAST_DAY_OF_CURRENT_CYCLE"]); export const usageInvoiceCycle = z.enum(["CALENDAR", "SUBSCRIPTION_ANNIVERSARY"]); export const usageInvoicing = z.object({frequency: usageInvoicingFrequency, payment_terms: paymentTerms, invoice_date: usageInvoiceDate, cycle: usageInvoiceCycle}); export const minimumCommitmentInvoicingFrequency = z.enum(["MONTHLY", "MONTHLY_PRORATED", "QUARTERLY", "SEMI_ANNUAL", "YEARLY"]); export const minimumCommitmentInvoicing = z.object({frequency: minimumCommitmentInvoicingFrequency, payment_terms: paymentTerms}); export const usageConfiguration = z.object({usage_invoicing: usageInvoicing, minimum_commitment_invoicing: minimumCommitmentInvoicing.optional(), minimum_commitment_cycle: z.enum(["MONTHLY", "CONTRACT"]).optional(), contract_level_minimum_commitment: usageCommitment.optional()}); export const exchangeRate = z.object({base: currencyCode, target: currencyCode, rate: z.string(), date: 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 invoiceStatus = z.enum(["UNPAID", "PAID", "PARTIALLY_PAID", "UNBILLED", "CREDITED", "PARTIALLY_CREDITED"]); export const calendarPeriod = z.object({start: z.string(), end: z.string()}); export const itemRevenue = z.object({period: calendarPeriod.optional(), pattern: revenuePattern.optional(), account_code: accountCode.optional()}); export const invoiceItem = z.object({id: z.string(), description: z.string(), revenue: itemRevenue, total_amount: roundedMonetaryAmount, total_discount: roundedMonetaryAmount, taxed_amount: roundedMonetaryAmount, gross_rate: roundedMonetaryAmount, quantity: z.string(), product_id: z.string(), external_references: z.array(externalReference), fields: fieldAssignments.optional()}); export const contractInvoice = z.object({id: z.string(), invoice_number: z.string(), invoice_date: z.string(), due_date: z.string(), status: invoiceStatus, total: roundedMonetaryAmount, taxed_amount: roundedMonetaryAmount, items: z.array(invoiceItem), external_references: z.array(externalReference)}); 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 expandedContract = z.object({id: z.string(), customer_id: z.string(), subsidiary_id: z.string(), name: z.string(), items: z.array(contractItem), status: contractStatus, start_date: z.string(), end_date: z.string().optional(), close_date: z.string(), invoicing: invoicing, usage_configuration: usageConfiguration.optional(), total_value: roundedMonetaryAmount, external_references: z.array(externalReference).optional(), exchange_rate: exchangeRate.optional(), metadata: z.record(z.string(), z.string()).optional(), 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, invoices: z.array(contractInvoice).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 contract * * POST /contracts */ export const createApiContracts = async (args: CreateApiContractsArgs, options?: CreateApiContractsOptions) => { 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 (args.idempotency_key != null) query.append("idempotency_key", String(args.idempotency_key)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/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(expandedContract, await res.json()) };