import {z} from 'zod' export type BuyerType = 'CUSTOMER' | 'PLATFORM_OWNER' | 'PARTNER'; export type Currency = 'USD' | 'CAD' | 'EUR' | 'JPY' | 'GBP' | 'KRW' | 'CHF' | 'SEK' | 'SGD' | 'MYR' | 'AUD' | 'MXN' | 'INR' | 'BRL' | 'DKK' | 'NZD' | 'NOK' | 'ZAR' | 'PHP' | 'CNY' | 'SAR' | 'GTQ' | 'IDR' | 'ARS' | 'COP' | 'PEN'; export type ServiceStrategy = 'CUSTOM' | 'IMMEDIATELY'; export type ServiceConfiguration = {date?: string | undefined, strategy?: ServiceStrategy | undefined}; export type BillingStrategy = 'CUSTOM' | 'NEXT_BILLING_CYCLE' | 'UPON_SERVICE_ACTIVATION'; export type BillingConfiguration = {date?: number | undefined, strategy?: BillingStrategy | undefined}; export type CustomPriceType = 'RESELLER_PURCHASE_PRICE' | 'MARKETPLACE_RESELLER_PURCHASE_PRICE'; export type PricingStrategy = 'FREE' | 'FLAT' | 'UNIT' | 'TIERED' | 'VOLUME' | 'VARIABLE_PRICE_STRATEGIES' | 'UNLIMITED' | 'CUSTOM'; export type PriceRange = {min: number, max?: number | undefined, price: number, salePrice?: unknown | undefined, wholesalePrice?: unknown | undefined}; export type Definition = {price?: number | undefined, priceRanges?: Array | undefined}; export type CustomPrice = {costId: string, priceType?: CustomPriceType | undefined, pricingStrategy?: PricingStrategy | undefined, definition?: Definition | undefined}; export type Unit = {quantity?: number | undefined, unit?: string | undefined}; export type CustomAttributes = {[key: string]: unknown}; export type ItemCustomAttributes = {vendorRequiredFields?: CustomAttributes | undefined, subscription?: CustomAttributes | undefined}; export type MinimumServiceLengthUnit = 'DAILY' | 'MONTHLY' | 'QUARTERLY' | 'SIX_MONTHS' | 'YEARLY' | 'TWO_YEARS' | 'THREE_YEARS'; export type GracePeriodUnit = 'NONE' | 'INFINITY' | 'DAY' | 'MONTH'; export type CancellationPeriodUnit = 'NONE' | 'DAY'; export type UnitContractTerms = {blockContractIncrease?: boolean | undefined, blockContractDecrease?: boolean | undefined, blockOriginalContractDecrease?: boolean | undefined}; export type TerminationFeeType = 'FIXED' | 'PERCENTAGE'; export type TerminationFee = {feeType?: TerminationFeeType | undefined, amount?: number | undefined, description?: string | undefined}; export type CustomContractConfiguration = {minimumServiceLength: number, minimumServiceLengthUnit: MinimumServiceLengthUnit, endOfContractGracePeriod?: number | undefined, endOfContractGracePeriodUnit?: GracePeriodUnit | undefined, contractCancellationPeriodLimit?: number | undefined, contractCancellationPeriodUnit?: CancellationPeriodUnit | undefined, continueWithoutContract?: boolean | undefined, autoExtensionPricingId?: string | undefined, terminationFeeGracePeriod?: number | undefined, terminationFeeGracePeriodUnit?: GracePeriodUnit | undefined, blockContractUpgrades?: boolean | undefined, blockContractDowngrades?: boolean | undefined, blockSwitchToShorterContract?: boolean | undefined, keepContractDateOnPlanChange?: boolean | undefined, alignWithParentCycleStartDate?: boolean | undefined, unitTerms?: {[key: string]: UnitContractTerms} | undefined, sourceId?: string | undefined, terminationFee?: TerminationFee | undefined, contractFee?: number | undefined}; export type ShoppingCartItem = {id?: string | undefined, referenceId?: string | undefined, subscriptionId?: string | undefined, pricingPlanId?: string | undefined, serviceConfiguration?: ServiceConfiguration | undefined, billingConfiguration?: BillingConfiguration | undefined, discountCode?: string | undefined, discountId?: string | undefined, customPrices?: Array | undefined, units?: Array | undefined, customAttributes?: ItemCustomAttributes | undefined, customContractConfiguration?: CustomContractConfiguration | undefined}; export type AssociationType = 'ADDON'; export type Association = {parentItemId?: string | undefined, childItemIds?: Array | undefined, type?: AssociationType | undefined}; export type Description = {defaultDescription?: string | undefined, localizedDescriptions?: {[key: string]: string} | undefined, params?: {[key: string]: string} | undefined}; export type RevenueShare = {appdirect?: number | undefined, channel?: number | undefined, vendor?: number | undefined}; export type Fee = {id?: string | undefined, externalId?: string | undefined, createdOn?: string | undefined, key?: string | undefined, currency?: string | undefined, amount?: number | undefined, description?: Description | undefined, revenueShare?: RevenueShare | undefined, itemIds?: Array | undefined, metadata?: {[key: string]: string} | undefined}; export type AccreditedAgent = {userId?: string | undefined, companyId?: string | undefined}; export type ShoppingCart = {id?: string | undefined, createdOn?: string | undefined, ownerUserId?: string | undefined, ownerCompanyId?: string | undefined, buyerType?: BuyerType | undefined, currency?: Currency | undefined, status?: string | undefined, isBlocked?: boolean | undefined, paymentMethodId?: string | undefined, preAuthId?: string | undefined, locale?: string | undefined, buyerUserId?: string | undefined, buyerCompanyId?: string | undefined, items?: Array | undefined, customAttributes?: ({purchase?: CustomAttributes | undefined, buyerUser?: CustomAttributes | undefined, buyerCompany?: CustomAttributes | undefined, ownerUser?: CustomAttributes | undefined, ownerCompany?: CustomAttributes | undefined}) | undefined, associations?: Array | undefined, fees?: Array | undefined, accreditedAgents?: Array | undefined}; export type CreateApiV3CheckoutShoppingCartsArgs = {'AD-ShoppingCart-Partner': string, body: ShoppingCart}; export type CreateApiV3CheckoutShoppingCartsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const buyerType = z.enum(["CUSTOMER", "PLATFORM_OWNER", "PARTNER"]); export const currency = z.enum(["USD", "CAD", "EUR", "JPY", "GBP", "KRW", "CHF", "SEK", "SGD", "MYR", "AUD", "MXN", "INR", "BRL", "DKK", "NZD", "NOK", "ZAR", "PHP", "CNY", "SAR", "GTQ", "IDR", "ARS", "COP", "PEN"]); export const serviceStrategy = z.enum(["CUSTOM", "IMMEDIATELY"]); export const serviceConfiguration = z.object({date: z.string().optional(), strategy: serviceStrategy.optional()}); export const billingStrategy = z.enum(["CUSTOM", "NEXT_BILLING_CYCLE", "UPON_SERVICE_ACTIVATION"]); export const billingConfiguration = z.object({date: z.number().optional(), strategy: billingStrategy.optional()}); export const customPriceType = z.enum(["RESELLER_PURCHASE_PRICE", "MARKETPLACE_RESELLER_PURCHASE_PRICE"]); export const pricingStrategy = z.enum(["FREE", "FLAT", "UNIT", "TIERED", "VOLUME", "VARIABLE_PRICE_STRATEGIES", "UNLIMITED", "CUSTOM"]); export const priceRange = z.object({min: z.number(), max: z.number().optional(), price: z.number(), salePrice: z.string().optional(), wholesalePrice: z.string().optional()}); export const definition = z.object({price: z.number().optional(), priceRanges: z.array(priceRange).optional()}); export const customPrice = z.object({costId: z.string(), priceType: customPriceType.optional(), pricingStrategy: pricingStrategy.optional(), definition: definition.optional()}); export const unit = z.object({quantity: z.number().optional(), unit: z.string().optional()}); export const customAttributes = z.record(z.string(), z.unknown()); export const itemCustomAttributes = z.object({vendorRequiredFields: customAttributes.optional(), subscription: customAttributes.optional()}); export const minimumServiceLengthUnit = z.enum(["DAILY", "MONTHLY", "QUARTERLY", "SIX_MONTHS", "YEARLY", "TWO_YEARS", "THREE_YEARS"]); export const gracePeriodUnit = z.enum(["NONE", "INFINITY", "DAY", "MONTH"]); export const cancellationPeriodUnit = z.enum(["NONE", "DAY"]); export const unitContractTerms = z.object({blockContractIncrease: z.boolean().optional(), blockContractDecrease: z.boolean().optional(), blockOriginalContractDecrease: z.boolean().optional()}); export const terminationFeeType = z.enum(["FIXED", "PERCENTAGE"]); export const terminationFee = z.object({feeType: terminationFeeType.optional(), amount: z.number().optional(), description: z.string().optional()}); export const customContractConfiguration = z.object({minimumServiceLength: z.number().int().gte(1), minimumServiceLengthUnit: minimumServiceLengthUnit, endOfContractGracePeriod: z.number().int().optional(), endOfContractGracePeriodUnit: gracePeriodUnit.optional(), contractCancellationPeriodLimit: z.number().int().optional(), contractCancellationPeriodUnit: cancellationPeriodUnit.optional(), continueWithoutContract: z.boolean().optional(), autoExtensionPricingId: z.string().optional(), terminationFeeGracePeriod: z.number().int().optional(), terminationFeeGracePeriodUnit: gracePeriodUnit.optional(), blockContractUpgrades: z.boolean().optional(), blockContractDowngrades: z.boolean().optional(), blockSwitchToShorterContract: z.boolean().optional(), keepContractDateOnPlanChange: z.boolean().optional(), alignWithParentCycleStartDate: z.boolean().optional(), unitTerms: z.record(z.string(), unitContractTerms).optional(), sourceId: z.string().optional(), terminationFee: terminationFee.optional(), contractFee: z.number().optional()}); export const shoppingCartItem = z.object({id: z.string().optional(), referenceId: z.string().optional(), subscriptionId: z.string().optional(), pricingPlanId: z.string().optional(), serviceConfiguration: serviceConfiguration.optional(), billingConfiguration: billingConfiguration.optional(), discountCode: z.string().optional(), discountId: z.string().optional(), customPrices: z.array(customPrice).optional(), units: z.array(unit).optional(), customAttributes: itemCustomAttributes.optional(), customContractConfiguration: customContractConfiguration.optional()}); export const associationType = z.literal("ADDON"); export const association = z.object({parentItemId: z.string().optional(), childItemIds: z.array(z.string()).optional(), type: associationType.optional()}); export const description = z.object({defaultDescription: z.string().optional(), localizedDescriptions: z.record(z.string(), z.string()).optional(), params: z.record(z.string(), z.string()).optional()}); export const revenueShare = z.object({appdirect: z.number().optional(), channel: z.number().optional(), vendor: z.number().optional()}); export const fee = z.object({id: z.string().optional(), externalId: z.string().optional(), createdOn: z.string().optional(), key: z.string().optional(), currency: z.string().optional(), amount: z.number().optional(), description: description.optional(), revenueShare: revenueShare.optional(), itemIds: z.array(z.string()).optional(), metadata: z.record(z.string(), z.string()).optional()}); export const accreditedAgent = z.object({userId: z.string().optional(), companyId: z.string().optional()}); export const shoppingCart = z.object({id: z.string().optional(), createdOn: z.string().optional(), ownerUserId: z.string().optional(), ownerCompanyId: z.string().optional(), buyerType: buyerType.optional(), currency: currency.optional(), status: z.string().optional(), isBlocked: z.boolean().optional(), paymentMethodId: z.string().optional(), preAuthId: z.string().optional(), locale: z.string().optional(), buyerUserId: z.string().optional(), buyerCompanyId: z.string().optional(), items: z.array(shoppingCartItem).optional(), customAttributes: z.object({purchase: customAttributes.optional(), buyerUser: customAttributes.optional(), buyerCompany: customAttributes.optional(), ownerUser: customAttributes.optional(), ownerCompany: customAttributes.optional()}).optional(), associations: z.array(association).optional(), fees: z.array(fee).optional(), accreditedAgents: z.array(accreditedAgent).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 }; /** * Create shopping carts * * POST /v3/checkout/shoppingCarts */ export const createApiV3CheckoutShoppingCarts = async (args: CreateApiV3CheckoutShoppingCartsArgs, options?: CreateApiV3CheckoutShoppingCartsOptions) => { const {baseUrl = "https://marketplace.appdirect.com/api", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['AD-ShoppingCart-Partner'] != null) headers.set("AD-ShoppingCart-Partner", String(args['AD-ShoppingCart-Partner'])) const url = `${baseUrl.replace(/\/+$/, '')}/v3/checkout/shoppingCarts${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(shoppingCart, await res.json()) };