import {z} from 'zod' export type CreateApiApiV2EmailCampaignsArgs = {body: {emailSenderId: number, subject: string, message: string, fromName?: (string | null) | undefined, replyToEmail?: (string | null) | undefined, recipients: {contactIds: Array, emails: Array, groupIds: Array}}}; export type CreateApiApiV2EmailCampaignsOptions = {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 emailCampaignStatisticTotals = z.object({recipients: z.number().int(), delivered: z.number().int(), rejected: z.number().int(), failed: z.number().int(), opened: z.number().int(), clicked: z.number().int(), spamReports: z.number().int(), unsubscribed: z.number().int()}); export const outboundEmailResponse = z.object({id: z.number().int(), sendTime: z.string(), fromName: z.string().nullable().optional(), fromEmail: z.string(), replyToEmail: z.string(), recipientFullName: z.string().nullable().optional(), recipientEmail: z.string().nullable().optional(), emailSubject: z.string(), emailContent: z.string(), source: z.enum(["emailCampaign", "ticket"]), status: z.enum(["pending", "sent", "delivered", "rejected", "failed", "opened", "clicked", "unsubscribed", "spam"]), cost: z.number(), statusReason: z.string().nullable().optional(), contactId: z.number().int().nullable().optional(), initiatorId: z.number().int()}); export const createEmailCampaignResponse = z.object({id: z.number().int(), status: z.enum(["idle", "sent", "in_progress", "failed", "delivered", "rejected", "error", "scheduledError"]), emailSenderId: z.number().int().nullable().optional(), startAt: z.string(), createdBy: userPersonalInfo, fromName: z.string().nullable().optional(), fromEmail: z.string(), replyToEmail: z.string(), subject: z.string(), html: z.string(), cost: z.number(), totals: emailCampaignStatisticTotals, outboundEmail: outboundEmailResponse.optional(), failedReason: z.enum(["lowBalance", "noRecipients", "noEmailSender", "unhandled"]).nullable().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 }; /** * Send email campaign * * POST /api/v2/email-campaigns */ export const createApiApiV2EmailCampaigns = async (args: CreateApiApiV2EmailCampaignsArgs, options?: CreateApiApiV2EmailCampaignsOptions) => { 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${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(createEmailCampaignResponse, await res.json()) };