import {z} from 'zod' export type CreateApiApiV2EmailCampaignsScheduleArgs = {body: {emailSenderId: number, subject: string, message: string, fromName?: (string | null) | undefined, replyToEmail?: (string | null) | undefined, recipients: {contactIds: Array, emails: Array, groupIds: Array}, scheduleParams: {startDateTime: string, timezone: string, rrule?: (string | null) | undefined}}}; export type CreateApiApiV2EmailCampaignsScheduleOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const userPersonalInfo = z.object({id: z.number().int(), firstName: z.string().nullable().optional(), lastName: z.string().nullable().optional(), avatarUrl: z.string().nullable().optional(), email: z.string().nullable().optional()}); export const scheduledEmailCampaignDetails = z.object({id: z.number().int(), status: z.enum(["scheduled", "active", "paused", "completed", "cancelled", "failed"]), emailSenderId: z.number().int().nullable().optional(), startAt: z.string(), endAt: z.string().nullable().optional(), nextSendAt: z.string().nullable().optional(), createdBy: userPersonalInfo, createdAt: z.string(), updatedAt: z.string(), type: z.enum(["once", "hourly", "daily", "weekly", "monthly", "yearly", "follow-up"]), fromName: z.string().nullable().optional(), fromEmail: z.string(), replyToEmail: z.string(), subject: z.string(), html: z.string(), recipientsCount: z.number().int(), sendingTimezone: z.string(), rrule: z.string().nullable().optional(), occurrenceSummary: z.string().nullable().optional()}); export const scheduleEmailCampaignResponse = z.object({campaign: scheduledEmailCampaignDetails, cost: z.number()}); 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 }; /** * Schedule new email campaign * * POST /api/v2/email-campaigns/schedule */ export const createApiApiV2EmailCampaignsSchedule = async (args: CreateApiApiV2EmailCampaignsScheduleArgs, options?: CreateApiApiV2EmailCampaignsScheduleOptions) => { const {baseUrl = "https://rest.textmagic.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") if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/email-campaigns/schedule${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(scheduleEmailCampaignResponse, await res.json()) };