import {z} from 'zod' export type Properties = unknown; export type RateSource = 'metric_units' | 'grants'; export type LedgerId = string; export type BillingMode = 'flat' | 'per_unit' | 'per_seat' | 'usage_sum' | 'last_metric_reported' | 'tiered_usage' | 'package' | 'minimum_commit'; export type RateAggregation = 'sum' | 'count' | 'latest' | 'max' | 'min'; export type UnitConversionMode = 'identity' | 'scale' | 'multiply'; export type RateTier = {up_to: string | null, unit_amount_minor_units: number, flat_amount_minor_units: number | null}; export type RateCardRateRequest = {source: RateSource, source_id: LedgerId, billing_mode: BillingMode, aggregation: RateAggregation, source_unit?: (string | null) | undefined, billing_unit?: (string | null) | undefined, conversion_mode?: (UnitConversionMode | null) | undefined, invoice_group_key?: (string | null) | undefined, unit_amount_minor_units?: (number | null) | undefined, unit_scale?: (string | null) | undefined, package_size?: (string | null) | undefined, included_quantity?: (string | null) | undefined, minimum_amount_minor_units?: (number | null) | undefined, commit_quantity?: (string | null) | undefined, commit_amount_minor_units?: (number | null) | undefined, markup_percent?: (string | null) | undefined, tiers?: (Array | null) | undefined, metadata?: Properties | undefined}; export type RateCardRequest = {name: string, description?: (string | null) | undefined, currency_code: string, metadata?: Properties | undefined, rates: Array}; export type CreateApiV2RateCardsArgs = {body: RateCardRequest}; export type CreateApiV2RateCardsOptions = {baseUrl: string, LedgerUpApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const ledgerId = z.string(); export const properties = z.unknown(); export const unixTimestamp = z.number().int(); export const rateSource = z.enum(["metric_units", "grants"]); export const billingMode = z.enum(["flat", "per_unit", "per_seat", "usage_sum", "last_metric_reported", "tiered_usage", "package", "minimum_commit"]); export const rateAggregation = z.enum(["sum", "count", "latest", "max", "min"]); export const unitConversionMode = z.enum(["identity", "scale", "multiply"]); export const rateTier = z.object({up_to: z.string().nullable(), unit_amount_minor_units: z.number().int(), flat_amount_minor_units: z.number().int().nullable()}); export const rateCardRate = z.object({id: ledgerId, source: rateSource, source_id: ledgerId, billing_mode: billingMode, aggregation: rateAggregation, source_unit: z.string().nullable(), billing_unit: z.string().nullable(), conversion_mode: unitConversionMode.nullable(), invoice_group_key: z.string().nullable(), unit_amount_minor_units: z.number().int().nullable(), unit_scale: z.string().nullable(), package_size: z.string().nullable(), included_quantity: z.string().nullable(), minimum_amount_minor_units: z.number().int().nullable(), commit_quantity: z.string().nullable(), commit_amount_minor_units: z.number().int().nullable(), markup_percent: z.string().nullable(), tiers: z.array(rateTier), metadata: properties, created_at: unixTimestamp, updated_at: unixTimestamp, archived_at: unixTimestamp.nullable()}); export const rateCard = z.object({id: ledgerId, name: z.string(), description: z.string().nullable(), currency_code: z.string(), metadata: properties, created_at: unixTimestamp, updated_at: unixTimestamp, archived_at: unixTimestamp.nullable(), rates: z.array(rateCardRate)}); 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 }; /** * Create a rate card. * * POST /v2/rate-cards */ export const createApiV2RateCards = async (args: CreateApiV2RateCardsArgs, options: CreateApiV2RateCardsOptions) => { const {baseUrl, fetch: fetchFn = fetch, LedgerUpApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (LedgerUpApiKey !== undefined) headers.set("x-api-key", LedgerUpApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v2/rate-cards${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(rateCard, await res.json()) };