import {z} from 'zod' export type RecordTransactionRequest = {currency: string, grossAmount: number, netAmount?: number | undefined, taxAmount?: number | undefined, amountCashNet?: number | undefined, amountPaid?: number | undefined, paidAt?: number | undefined, externalId?: string | undefined, transactionId?: string | undefined, customerId?: string | undefined, orderId?: string | undefined, paymentId?: string | undefined, invoiceId?: string | undefined, subscriptionId?: string | undefined, paymentIntentId?: string | undefined, chargeId?: string | undefined, description?: string | undefined, invoiceTotal?: number | undefined, invoiceTotalExcludingTax?: number | undefined, invoiceSubtotalExcludingTax?: number | undefined, totalTaxAmount?: number | undefined, totalTaxAmounts?: Array<{[key: string]: unknown}> | undefined, totalTaxes?: Array<{[key: string]: unknown}> | undefined}; export type CreateApiCampaignIdParticipantParticipantIdOrEmailTransactionArgs = {id: string, participantIdOrEmail: string, body: RecordTransactionRequest}; export type CreateApiCampaignIdParticipantParticipantIdOrEmailTransactionOptions = {baseUrl?: string | undefined, apiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const recordTransactionResponse = z.union([z.object({success: z.literal(true), firstSale: z.boolean(), duplicate: z.literal(false), message: z.string()}), z.object({success: z.literal(false), duplicate: z.literal(true), commissionsCreated: z.number().int(), duplicateFields: z.array(z.string()), matchingCommissionIds: z.array(z.string()), message: z.string()})]); 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 }; /** * Record affiliate transaction * * POST /campaign/{id}/participant/{participantIdOrEmail}/transaction */ export const createApiCampaignIdParticipantParticipantIdOrEmailTransaction = async (args: CreateApiCampaignIdParticipantParticipantIdOrEmailTransactionArgs, options?: CreateApiCampaignIdParticipantParticipantIdOrEmailTransactionOptions) => { const {baseUrl = "https://api.growsurf.com/v2", fetch: fetchFn = fetch, apiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKeyAuth !== undefined) headers.set('authorization', `Bearer ${apiKeyAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/campaign/${encodeURIComponent(String(args.id))}/participant/${encodeURIComponent(String(args.participantIdOrEmail))}/transaction${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(recordTransactionResponse, await res.json()) };