import {z} from 'zod' export type ApplyCommerceDiscountRequest = {discount_id: string}; export type CreateApiBillingSubscriptionItemsSubscriptionItemIdDiscountsArgs = {subscription_item_id: string, body: ApplyCommerceDiscountRequest}; export type CreateApiBillingSubscriptionItemsSubscriptionItemIdDiscountsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const commerceMoneyResponse = z.object({amount: z.number().int(), amount_formatted: z.string(), currency: z.string(), currency_symbol: z.string()}); export const commerceDiscountRedemptionResponse = z.object({object: z.literal("commerce_discount_redemption"), id: z.string(), subscription_item_id: z.string(), discount_id: z.string(), name: z.string().optional(), source: z.enum(["promotion", "manual", "promo_code"]), promo_code: z.string().optional(), effect: z.enum(["percentage", "fixed_amount"]).optional(), percent_off: z.number().nullable().optional(), amount_off: commerceMoneyResponse.nullable().optional(), amount: commerceMoneyResponse.nullable().optional(), cycles_remaining: z.number().int().nullable(), cycles_applied: z.number().int(), status: z.enum(["active", "exhausted", "removed"]).optional(), redeemed_at: z.number().int(), redeemed_by: z.string().nullable()}); 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 }; /** * Apply a discount to a subscription item * * POST /billing/subscription_items/{subscription_item_id}/discounts */ export const createApiBillingSubscriptionItemsSubscriptionItemIdDiscounts = async (args: CreateApiBillingSubscriptionItemsSubscriptionItemIdDiscountsArgs, options?: CreateApiBillingSubscriptionItemsSubscriptionItemIdDiscountsOptions) => { const {baseUrl = "https://api.clerk.com/v1", 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(/\/+$/, '')}/billing/subscription_items/${encodeURIComponent(String(args.subscription_item_id))}/discounts${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(commerceDiscountRedemptionResponse, await res.json()) };