import {z} from 'zod' export type GetApiV2CallsArgs = {pageSize?: number | undefined, page?: number | undefined, field?: ('createdAt' | 'duration') | undefined, order?: ('ASC' | 'DESC') | undefined, direction?: (Array<'inbound' | 'outgoing'>) | undefined, status?: ('answered' | 'missed' | 'voicemail' | 'active' | 'geniusAnswering') | undefined, userId?: Array | undefined, clientId?: Array | undefined, jobId?: Array | undefined, leadId?: Array | undefined, adGroupId?: Array | undefined, tags?: Array | undefined, sentiment?: (Array<'great' | 'positive' | 'neutral' | 'negative'>) | undefined, intent?: (Array<'booking' | 'callbackRequest' | 'existingBooking' | 'spam' | 'other'>) | undefined, durationOperator?: ('under' | 'over') | undefined, duration?: number | undefined, dateProperty?: 'created' | undefined, dateOperator?: ('prev' | 'next' | 'between') | undefined, date?: string | undefined, Authorization: string}; export type GetApiV2CallsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const responseCallInsightsV2Dto = z.object({sentiment: z.enum(["great", "positive", "neutral", "negative"]).nullable().optional(), intent: z.enum(["booking", "callbackRequest", "existingBooking", "spam", "other"]).nullable().optional(), dispatcherScore: z.number().nullable().optional(), objection: z.enum(["price", "serviceNotOffered", "outOfServiceArea", "noAvailability", "Dispatcher experience issue", "notReadyToBook", "Callback needed", "disconnected", "other"]).nullable().optional(), pricingDiscussed: z.boolean().optional(), booked: z.boolean().optional()}); export const responseCallV2Dto = z.object({id: z.string().optional(), direction: z.enum(["inbound", "outgoing"]).optional(), from: z.string().optional(), to: z.string().optional(), callMaskingNumber: z.string().nullable().optional(), duration: z.number().optional(), status: z.enum(["answered", "missed", "voicemail", "active", "geniusAnswering"]).optional(), hasRecording: z.boolean().optional(), flowName: z.string().nullable().optional(), adGroupId: z.string().nullable().optional(), clientId: z.string().nullable().optional(), clientName: z.string().nullable().optional(), jobId: z.string().nullable().optional(), leadId: z.string().nullable().optional(), answeredByUserId: z.string().nullable().optional(), answeredByUserName: z.string().nullable().optional(), calledByUserId: z.string().nullable().optional(), calledByUserName: z.string().nullable().optional(), tags: z.array(z.string()).optional(), insights: responseCallInsightsV2Dto.nullable().optional(), updatedAt: z.string().nullable().optional(), createdAt: z.string().optional()}); export const responseCallsDateRangeV2Dto = z.object({dateProperty: z.literal("created").optional(), from: z.string().nullable().optional(), to: z.string().nullable().optional()}); export const responseCallsV2Dto = z.object({pageSize: z.number().optional(), page: z.number().optional(), totalResults: z.number().optional(), hasMore: z.boolean().optional(), data: z.array(responseCallV2Dto).optional(), dateRange: responseCallsDateRangeV2Dto.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 }; /** * Retrieve a list of Calls * * GET /v2/calls */ export const getApiV2Calls = async (args: GetApiV2CallsArgs, options?: GetApiV2CallsOptions) => { const {baseUrl = "https://api.workiz.com/crm/api", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (args.page != null) query.append("page", String(args.page)) if (args.field != null) query.append("field", String(args.field)) if (args.order != null) query.append("order", String(args.order)) for (const item of args.direction ?? []) query.append("direction", String(item)) if (args.status != null) query.append("status", String(args.status)) for (const item of args.userId ?? []) query.append("userId", String(item)) for (const item of args.clientId ?? []) query.append("clientId", String(item)) for (const item of args.jobId ?? []) query.append("jobId", String(item)) for (const item of args.leadId ?? []) query.append("leadId", String(item)) for (const item of args.adGroupId ?? []) query.append("adGroupId", String(item)) for (const item of args.tags ?? []) query.append("tags", String(item)) for (const item of args.sentiment ?? []) query.append("sentiment", String(item)) for (const item of args.intent ?? []) query.append("intent", String(item)) if (args.durationOperator != null) query.append("durationOperator", String(args.durationOperator)) if (args.duration != null) query.append("duration", String(args.duration)) if (args.dateProperty != null) query.append("dateProperty", String(args.dateProperty)) if (args.dateOperator != null) query.append("dateOperator", String(args.dateOperator)) if (args.date != null) query.append("date", String(args.date)) if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) const url = `${baseUrl.replace(/\/+$/, '')}/v2/calls${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(responseCallsV2Dto, await res.json()) };