import {z} from 'zod' export type OpportunityCurrency = '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 BillingStrategy = 'CUSTOM' | 'NEXT_BILLING_CYCLE' | 'UPON_SERVICE_ACTIVATION'; export type BillingConfiguration = {date?: number | undefined, strategy?: BillingStrategy | undefined}; export type ProvisioningStrategy = 'CUSTOM' | 'IMMEDIATELY'; export type OpportunityItem = {id?: string | undefined, parentItemId?: string | undefined, pricingPlanId?: string | undefined, units?: Array | undefined, productId?: string | undefined, subscriptionCustomAttributes?: {[key: string]: Array} | undefined, vendorRequiredFields?: {[key: string]: Array} | undefined, provisioningConfiguration?: ({date?: number | undefined, strategy?: ProvisioningStrategy | undefined}) | undefined, billingConfiguration?: ({date?: number | undefined, strategy?: BillingStrategy | undefined}) | undefined}; export type OpportunityCreationRequest = {customerCompanyId: string, customerId: string, ownerCompanyId: string, ownerId: string, currency?: OpportunityCurrency | undefined, items: Array, purchaseEffectiveDate?: number | undefined, name?: string | undefined, createdByCompanyId?: string | undefined, createdById?: string | undefined, purchaseCustomAttributes?: {[key: string]: Array} | undefined}; export type CreateApiAssistedSalesV1OpportunitiesArgs = {context?: ('RESELLER' | 'SSR') | undefined, body: OpportunityCreationRequest}; export type CreateApiAssistedSalesV1OpportunitiesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const user = z.object({id: z.string().optional(), email: z.string().optional(), firstName: z.string().optional(), lastName: z.string().optional(), company: z.object({id: z.string().optional(), name: z.string().optional(), isReseller: z.boolean().optional()}).optional()}); export const opportunityCurrency = 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 opportunityStatus = z.enum(["OPEN", "CLOSED", "PENDING_REVIEW"]); 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 provisioningStrategy = z.enum(["CUSTOM", "IMMEDIATELY"]); export const opportunityItem = z.object({id: z.string().optional(), parentItemId: z.string().optional(), pricingPlanId: z.string().optional(), units: z.array(billingConfiguration).optional(), productId: z.string().optional(), subscriptionCustomAttributes: z.record(z.string(), z.array(z.string())).optional(), vendorRequiredFields: z.record(z.string(), z.array(z.string())).optional(), provisioningConfiguration: z.object({date: z.number().optional(), strategy: provisioningStrategy.optional()}).optional(), billingConfiguration: z.object({date: z.number().optional(), strategy: billingStrategy.optional()}).optional()}); export const availableAction = z.enum(["EDIT", "FINALIZE", "SUBMIT_FOR_REVIEW", "ADD_PRODUCT", "SET_CUSTOM_PRICE", "SET_CUSTOM_CONTRACT", "SET_PROVISIONING_DATE", "SET_BILLING_DATE", "CHANGE_OPPORTUNITY_OWNER"]); export const restriction = z.enum(["CANNOT_FINALIZE_WITH_INACTIVE_CUSTOMER", "CANNOT_SUBMIT_WITH_INACTIVE_CUSTOMER"]); export const opportunity = z.object({id: z.string().optional(), ownerUser: user.optional(), customerUser: user.optional(), createdOn: z.number().optional(), currency: opportunityCurrency.optional(), purchaseEffectiveDate: z.number().optional(), name: z.string().optional(), status: opportunityStatus.optional(), items: z.array(opportunityItem).optional(), purchaseId: z.string().optional(), purchaseNumber: z.string().optional(), availableActions: z.array(availableAction).optional(), actionRestrictions: z.object({entry: z.array(restriction).optional()}).optional(), purchaseCustomAttributes: z.record(z.string(), z.array(z.string())).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 opportunity * * POST /assistedSales/v1/opportunities */ export const createApiAssistedSalesV1Opportunities = async (args: CreateApiAssistedSalesV1OpportunitiesArgs, options?: CreateApiAssistedSalesV1OpportunitiesOptions) => { 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.context != null) query.append("context", String(args.context)) const url = `${baseUrl.replace(/\/+$/, '')}/assistedSales/v1/opportunities${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(opportunity, await res.json()) };