import {z} from 'zod' export type ProductType = 'PRODUCT' | 'BUNDLE'; 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 MilestoneExpectedOffset = {count: number, unit: 'DAYS' | 'MONTHS' | 'YEARS'}; export type MilestoneTemplateRequest = {key: string, name: string, sequence: number, value: string, expected_offset?: (MilestoneExpectedOffset | null) | undefined}; export type ProgressPlanTemplateRequest = {measure: ProgressMeasure, value_mode: MilestoneValueMode, milestones: Array}; export type AccountCode = string; export type ExternalReference = {type: string, id: string, url?: string | undefined}; export type FieldAssignments = Array<{field_id: string, field_value_id: string}>; export type BundleInvoiceDisplay = 'BUNDLE_AND_COMPONENTS' | 'BUNDLE_LINE_ONLY'; export type BundleComponentRequest = {product_id: string, quantity: unknown}; export type BundleRequest = {invoice_display?: BundleInvoiceDisplay | undefined, components: Array}; export type ProductRequest = {type?: ProductType | undefined, name: string, description: string, price: Price, include_in_arr_mrr: boolean, include_in_ssp?: (boolean | null) | undefined, revenue_pattern?: RevenuePattern | undefined, progress_plan_template?: (ProgressPlanTemplateRequest | null) | undefined, account_code?: AccountCode | undefined, status?: ('ACTIVE' | 'INACTIVE') | undefined, external_references?: Array | undefined, fields?: FieldAssignments | undefined, bundle?: BundleRequest | undefined}; export type CreateApiProductsArgs = {body: ProductRequest}; export type CreateApiProductsOptions = {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 revenuePattern = z.enum(["DAILY", "EVEN_PERIOD", "PROGRESS"]); export const progressMeasure = z.literal("MILESTONES"); export const milestoneValueMode = z.enum(["PERCENTAGE", "AMOUNT"]); export const milestoneExpectedOffset = z.object({count: z.number().int().gte(0), unit: z.enum(["DAYS", "MONTHS", "YEARS"])}); export const milestoneTemplate = z.object({key: z.string(), name: z.string().min(1), sequence: z.number().int().gte(1), value: z.string(), expected_offset: milestoneExpectedOffset.nullable().optional(), id: z.string()}); export const progressPlanTemplate = z.object({measure: progressMeasure, value_mode: milestoneValueMode, milestones: z.array(milestoneTemplate)}); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const accountCode = z.string(); export const bundleInvoiceDisplay = z.enum(["BUNDLE_AND_COMPONENTS", "BUNDLE_LINE_ONLY"]); export const bundleComponent = z.object({product_id: z.string(), quantity: z.string()}); export const bundleDetails = z.object({invoice_display: bundleInvoiceDisplay, components: z.array(bundleComponent)}); export const product = z.object({id: z.string(), type: productType, name: z.string(), description: z.string(), price: price, include_in_arr_mrr: z.boolean(), include_in_ssp: z.boolean().optional(), revenue_pattern: revenuePattern.optional(), progress_plan_template: progressPlanTemplate.nullable().optional(), external_references: z.array(externalReference).optional(), fields: fieldAssignments, status: z.enum(["ACTIVE", "INACTIVE"]), account_code: accountCode.optional(), bundle: bundleDetails.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 product * * POST /products */ export const createApiProducts = async (args: CreateApiProductsArgs, options?: CreateApiProductsOptions) => { 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(/\/+$/, '')}/products${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(product, await res.json()) };