import {z} from 'zod' export type Device = {appId?: string | undefined, deviceModel?: string | undefined, os?: string | undefined, locale?: string | undefined, clientVersion?: ('native' | 'esputnik-1') | undefined, appVersion?: string | undefined, active?: boolean | undefined}; export type WebPushSubscription = {appId?: number | undefined, userAgent?: string | undefined, userAgentVersion?: string | undefined, userAgentLanguage?: string | undefined, os?: string | undefined, ip?: string | undefined, subscriptionPage?: string | undefined, swActiveVersion?: string | undefined}; export type Channel = {type?: ('email' | 'sms' | 'viber' | 'mobilepush' | 'webpush' | 'appinbox' | 'widget' | 'inapp' | 'telegrambot') | undefined, value?: string | undefined, device?: Device | undefined, webPushSubscription?: WebPushSubscription | undefined, appUuid?: string | undefined}; export type Address = {region?: string | undefined, town?: string | undefined, address?: string | undefined, postcode?: string | undefined, countryCode?: (string | null) | undefined}; export type ContactField = {id?: number | undefined, value?: string | undefined}; export type GroupDto = {id?: number | undefined, name?: string | undefined, type?: string | undefined}; export type Contact = {firstName?: string | undefined, lastName?: string | undefined, channels?: Array | undefined, address?: Address | undefined, fields?: Array | undefined, addressBookId?: number | undefined, id?: number | undefined, externalCustomerId?: string | undefined, groups?: Array | undefined, languageCode?: string | undefined, timeZone?: string | undefined, marketId?: string | undefined}; export type ContactsBulkUpdate = {contacts: Array, dedupeOn: 'email' | 'sms' | 'push' | 'email_or_sms' | 'id' | 'externalCustomerId' | 'fieldId', fieldId?: number | undefined, contactFields?: (Array<'firstName' | 'contactKey' | 'ordersInfo' | 'lastName' | 'languageCode' | 'timeZone' | 'marketId' | 'email' | 'sms' | 'mobilepush' | 'webpush' | 'address' | 'town' | 'region' | 'externalCustomerId' | 'postcode' | 'countryCode' | 'firstName' | 'contactKey' | 'lastName' | 'languageCode' | 'timeZone' | 'marketId' | 'email' | 'sms' | 'mobilepush' | 'webpush' | 'address' | 'town' | 'region' | 'externalCustomerId' | 'postcode' | 'countryCode'>) | undefined, customFieldsIDs?: Array | undefined, groupNames?: Array | undefined, groupNamesExclude?: Array | undefined, restoreDeleted?: boolean | undefined, eventKeyForNewContacts?: string | undefined}; export type CreateApiApiV1ContactsArgs = {body: ContactsBulkUpdate}; export type CreateApiApiV1ContactsOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const device = z.object({appId: z.string().optional(), deviceModel: z.string().optional(), os: z.string().optional(), locale: z.string().optional(), clientVersion: z.enum(["native", "esputnik-1"]).optional(), appVersion: z.string().optional(), active: z.boolean().optional()}); export const webPushSubscription = z.object({appId: z.number().int().optional(), userAgent: z.string().optional(), userAgentVersion: z.string().optional(), userAgentLanguage: z.string().optional(), os: z.string().optional(), ip: z.string().optional(), subscriptionPage: z.string().optional(), swActiveVersion: z.string().optional()}); export const channel = z.object({type: z.enum(["email", "sms", "viber", "mobilepush", "webpush", "appinbox", "widget", "inapp", "telegrambot"]).optional(), value: z.string().optional(), device: device.optional(), webPushSubscription: webPushSubscription.optional(), appUuid: z.string().optional()}); export const address = z.object({region: z.string().optional(), town: z.string().optional(), address: z.string().optional(), postcode: z.string().optional(), countryCode: z.string().max(2).nullable().optional()}); export const contactField = z.object({id: z.number().int().optional(), value: z.string().optional()}); export const groupDto = z.object({id: z.number().int().optional(), name: z.string().optional(), type: z.string().optional()}); export const failedContact = z.object({firstName: z.string().optional(), lastName: z.string().optional(), channels: z.array(channel), address: address.optional(), fields: z.array(contactField).optional(), addressBookId: z.number().int().optional(), id: z.number().int().optional(), contactKey: z.string().optional(), groups: z.array(groupDto).optional(), languageCode: z.string().optional(), timeZone: z.string().optional(), marketId: z.string().optional(), error: z.string().optional()}); export const contactBulkUpdateResult = z.object({failedContacts: z.array(failedContact).optional(), asyncSessionId: z.string().optional(), errorMessage: 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 }; /** * Add/update contacts * * POST /api/v1/contacts */ export const createApiApiV1Contacts = async (args: CreateApiApiV1ContactsArgs, options?: CreateApiApiV1ContactsOptions) => { const {baseUrl = "https://api.reteno.com", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json; charset=UTF-8") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/contacts${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(contactBulkUpdateResult, await res.json()) };