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 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 CountryCode = string; export type TaxRate = {percentage: unknown, tax_amount?: RoundedMonetaryAmount | undefined, country: CountryCode, type: 'VAT' | 'SALES_TAX', description: string}; export type AmendmentEffectiveFrom = 'AS_OF_AMENDMENT_DATE' | 'END_OF_CURRENT_BILLING_CYCLE'; export type AmendFullContractItemRequest = {product_id: string, price: Price, quantity: number, revenue_pattern?: RevenuePattern | undefined, discount?: Discount | undefined, tax_rate?: TaxRate | undefined, start_date: string, end_date?: string | undefined, effective_from?: AmendmentEffectiveFrom | undefined, amending?: string | 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 PreviewContractAmendmentRequest = {amendment_date: string, items: Array, invoicing: Invoicing}; export type CreateApiContractsContractIdAmendmentsPreviewArgs = {contract_id: string, body: PreviewContractAmendmentRequest}; export type CreateApiContractsContractIdAmendmentsPreviewOptions = {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 }; /** * Previews contract amendment * * POST /contracts/{contract_id}/amendments/preview */ export const createApiContractsContractIdAmendmentsPreview = async (args: CreateApiContractsContractIdAmendmentsPreviewArgs, options?: CreateApiContractsContractIdAmendmentsPreviewOptions) => { 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(/\/+$/, '')}/contracts/${encodeURIComponent(String(args.contract_id))}/amendments/preview${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()) };