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 CreateApiContractsPreviewInvoiceScheduleArgs = {body: CreateContractRequest}; export type CreateApiContractsPreviewInvoiceScheduleOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const currencyCode = z.string(); export const roundedMonetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const billingPeriod = z.object({start: z.string(), end: z.string()}); export const contractInvoiceScheduleItem = z.object({contract_item_id: z.string().optional(), description: z.string(), quantity: z.string(), price_type: z.enum(["FIXED", "USAGE", "USAGE_COMMITMENT"]), unit_amount: roundedMonetaryAmount, total_amount: roundedMonetaryAmount, billing_period: billingPeriod}); export const contractInvoiceScheduleEntry = z.object({issue_date: z.string(), currency: z.string(), total: roundedMonetaryAmount, items: z.array(contractInvoiceScheduleItem)}); export const contractInvoiceSchedule = z.object({invoices: z.array(contractInvoiceScheduleEntry)}); 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 }; /** * Preview the invoice schedule for a contract * * POST /contracts/preview-invoice-schedule */ export const createApiContractsPreviewInvoiceSchedule = async (args: CreateApiContractsPreviewInvoiceScheduleArgs, options?: CreateApiContractsPreviewInvoiceScheduleOptions) => { 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/preview-invoice-schedule${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(contractInvoiceSchedule, await res.json()) };