import {z} from 'zod' export type ConversationSort = {orderBy?: ('CREATED_DATE_TIME' | 'SUBJECT' | 'EMAIL' | 'LAST_MESSAGE_CREATED_DATE_TIME' | 'LAST_MESSAGE_TEXT') | undefined, direction?: ('ASC' | 'DESC') | undefined}; export type StringFilter = {equal?: string | undefined, notEqual?: string | undefined, greaterThan?: string | undefined, greaterThanEqual?: string | undefined, lessThan?: string | undefined, lessThanEqual?: string | undefined, contain?: string | undefined}; export type Ids = {in?: Array | undefined}; export type AttachedEntityFilter = {id?: Ids | undefined}; export type ResolutionStatusListFilter = {in?: (Array<'OPEN' | 'CLOSED' | 'DRAFT'>) | undefined, notIn?: (Array<'OPEN' | 'CLOSED' | 'DRAFT'>) | undefined}; export type ReadStatusListFilter = {in?: (Array<'READ' | 'UNREAD'>) | undefined, notIn?: (Array<'READ' | 'UNREAD'>) | undefined}; export type CompanyIdFilter = {in?: Array | undefined}; export type ConversationFilterParam = {subject?: StringFilter | undefined, attachedEntity?: AttachedEntityFilter | undefined, resolutionStatus?: ResolutionStatusListFilter | undefined, readStatus?: ReadStatusListFilter | undefined, authorUserId?: StringFilter | undefined, authorEmail?: StringFilter | undefined, company?: CompanyIdFilter | undefined}; export type ConversationQueryParam = {cursor?: (string | null) | undefined, limit?: number | undefined, sort?: ConversationSort | undefined, filter?: ConversationFilterParam | undefined}; export type CreateApiV6ConversationsQueryArgs = {body: ConversationQueryParam}; export type CreateApiV6ConversationsQueryOptions = {baseUrl?: string | undefined, EmbedToken?: string | undefined, fetch?: typeof fetch | undefined}; export const companyExpanded = z.object({id: z.string(), name: z.string().optional()}); export const authorInfo = z.object({userId: z.string(), email: z.string().nullable()}); export const latestMessageDto = z.object({id: z.string(), author: authorInfo, text: z.string()}); export const conversationGetDto = z.object({id: z.string(), attachedEntityId: z.string().nullable(), company: companyExpanded, subject: z.string(), author: authorInfo, latestMessage: latestMessageDto, status: z.enum(["ACTIVE", "INACTIVE", "REMOVED"]), readStatus: z.enum(["READ", "UNREAD"]), resolutionStatus: z.enum(["OPEN", "CLOSED", "DRAFT"]), createdDateTime: z.string(), lastUpdatedDateTime: z.string()}); export const responseCursor = z.object({after: z.string().optional(), before: z.string().optional()}); export const paginatedResponseConversationGetDto = z.object({result: z.enum(["SUCCESS", "FAILURE"]).optional(), data: z.array(conversationGetDto).optional(), cursor: responseCursor.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 }; /** * Query conversations * * POST /v6/conversations/query */ export const createApiV6ConversationsQuery = async (args: CreateApiV6ConversationsQueryArgs, options?: CreateApiV6ConversationsQueryOptions) => { const {baseUrl = "https://sandbox.tight.com", fetch: fetchFn = fetch, EmbedToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (EmbedToken !== undefined) headers.set('authorization', `Bearer ${EmbedToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/v6/conversations/query${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(paginatedResponseConversationGetDto, await res.json()) };