import {z} from 'zod' export type GetApiMessagesArgs = {patient?: string | undefined, key?: ('chatRequest' | 'chatRequestInsecure') | undefined, from?: string | undefined, to?: string | undefined, type?: ('inbound' | 'outbound') | undefined, voiceAnsweredBy?: ('human' | 'fax' | 'unknown' | 'machine-start' | 'machine-end-beep' | 'machine-end-silence' | 'machine-end-other') | undefined, ref?: ('reminder' | 'referral-reminder' | 'feedback-reminder' | 'followup' | 'outbound-referral-reminder' | 'form-reminder' | 'reschedule' | 'waitlist' | 'appointment-offer' | 'chat-notification' | 'pin-verification' | 'chat' | 'chat-audit' | 'chat-audit-tz' | 'feedback' | 'waitlist-offer' | 'referral-followup' | 'outbound-referral-outreach' | 'referral-redirect' | 'broadcast' | 'generic' | 'stop' | 'bot:followup' | 'telehealth' | 'waiting-room-patient') | undefined, refId?: string | undefined, patientMessageTemplate?: string | undefined, outboundMessage?: string | undefined, status?: ('sent' | 'pending' | 'delivered' | 'undelivered' | 'opened' | 'skipped') | undefined, externalStatus?: (Array<'code' | 'reason'>) | undefined, skippedStatusReason?: string | undefined, channel?: ('sms' | 'email' | 'voice' | 'inapp' | 'chat' | 'fax' | 'whatsapp') | undefined, text?: string | undefined, classification?: ('positive' | 'negative' | 'irregular' | 'recognized-keywords' | 'unclassified') | undefined, secure?: boolean | undefined, automated?: boolean | undefined, visibility?: ('public' | 'private' | 'internal') | undefined, file?: string | undefined, recipient?: string | undefined, recipientType?: ('doctor' | 'staff' | 'patient') | undefined, shouldForceContactWithNotifyTo?: boolean | undefined, appointment?: string | undefined, provider?: string | undefined, appointmentType?: string | undefined, followup?: string | undefined, recall?: string | undefined, referral?: string | undefined, messageFailure?: string | undefined, groups?: string | undefined, language?: ('ar' | 'bn' | 'cn' | 'de' | 'en' | 'es' | 'fa' | 'fl' | 'fr' | 'gr' | 'gu' | 'hi' | 'ht' | 'hy' | 'it' | 'ja' | 'km' | 'ko' | 'mr' | 'my' | 'pa' | 'pl' | 'pt' | 'ru' | 'so' | 'th' | 'ti' | 'ur' | 'vi' | 'zh-t' | 'zh') | undefined, createdBy?: string | undefined, updatedBy?: string | undefined, createdAt?: string | undefined, updatedAt?: string | undefined, page?: number | undefined, limit?: number | undefined, _populate?: string | undefined, _select?: string | undefined}; export type GetApiMessagesOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const idParam = z.string().min(24).max(24); export const userParam = z.string().min(24).max(24); export const deletedParam = z.union([z.literal(0), z.literal(1)]); export const createdByParam = z.string().min(24).max(24); export const updatedByParam = z.string().min(24).max(24); export const createdAtParam = z.string(); export const updatedAtParam = z.string(); export const ref = z.enum(["reminder", "referral-reminder", "feedback-reminder", "followup", "outbound-referral-reminder", "form-reminder", "reschedule", "waitlist", "appointment-offer", "chat-notification", "pin-verification", "chat", "chat-audit", "chat-audit-tz", "feedback", "waitlist-offer", "referral-followup", "outbound-referral-outreach", "referral-redirect", "broadcast", "generic", "stop", "bot:followup", "telehealth", "waiting-room-patient"]); export const language = z.enum(["ar", "bn", "cn", "de", "en", "es", "fa", "fl", "fr", "gr", "gu", "hi", "ht", "hy", "it", "ja", "km", "ko", "mr", "my", "pa", "pl", "pt", "ru", "so", "th", "ti", "ur", "vi", "zh-t", "zh"]); export const externalId = z.object({source: z.enum(["gcalendar", "successehs", "drchrono", "dentrix", "webpt", "theraoffice", "mi7", "practicefusion", "advancedmd", "acomrapidpm", "kareo", "nextech", "mwtherapy", "clinicient", "carecloud", "eclinicalmobile", "duxware", "labretriever", "optimispt", "referral", "recall", "allscriptspm", "lytec", "brightree", "fullslate", "nuemd", "centricityps", "officeally", "greenwayintergy", "compulink", "adspm", "dsnpm", "lumamock", "medicalmastermind", "meditouch", "healthnautica", "ezemrx", "hl7", "amazingcharts", "greenwayprimesuite", "raintree", "athenahealth", "revflow", "eclinicalworks10e", "hl7pickup", "mindbody", "eclinicalworkssql", "nextgen", "practiceperfect", "avimark", "clinix", "keymedical", "mdoffice", "webedoctor", "emapm", "medinformatix", "imsgo", "emds", "allscriptsunity", "medevolve", "caretracker", "clearpractice", "valant", "micromd", "systemedx", "medicalmaster", "athenamdp", "gmed", "roche", "onetouch", "somnoware", "managementplus", "lumacare", "nextechfhir", "curemd", "epic", "phoenixortho", "ezderm", "ggastromobile", "epicconfirmationpickup", "cerner", "allmeds", "oncoemrfilepickup", "imedicware", "modmedfhir", "clinux", "acuityscheduling", "medstreaming", "isalus", "meditechexpanse", "openemr", "genericfhir", "nextechpracticeplus", "sms", "voice", "email", "none"]).optional(), value: z.string().optional()}); export const messageResponse = z.object({_id: idParam.optional(), user: userParam.optional(), deleted: deletedParam.optional(), createdBy: createdByParam.optional(), updatedBy: updatedByParam.optional(), createdAt: createdAtParam.optional(), updatedAt: updatedAtParam.optional(), patient: z.string().min(24).max(24).optional(), key: z.string().optional(), from: z.string().optional(), to: z.string().optional(), type: z.enum(["inbound", "outbound"]).optional(), voiceAnsweredBy: z.enum(["human", "fax", "unknown", "machine-start", "machine-end-beep", "machine-end-silence", "machine-end-other"]).optional(), ref: ref.optional(), refId: z.string().min(24).max(24).optional(), patientMessageTemplate: z.string().min(24).max(24).optional(), outboundMessage: z.string().min(24).max(24).optional(), status: z.enum(["sent", "pending", "delivered", "undelivered", "opened", "skipped"]).optional(), skippedStatusReason: z.string().optional(), language: language.optional(), externalStatus: z.object({code: z.string().optional(), reason: z.string().optional()}).optional(), channel: z.enum(["sms", "email", "voice", "inapp", "chat", "fax", "whatsapp"]).optional(), notifyTo: z.array(z.object({channel: z.enum(["sms", "email", "voice", "inapp", "chat", "fax", "whatsapp"]).optional(), to: z.string().optional()})).optional(), shouldForceContactWithNotifyTo: z.boolean().optional(), text: z.string().optional(), classification: z.enum(["positive", "negative", "irregular", "recognized-keywords", "unclassified"]).optional(), externalId: externalId.optional(), secure: z.boolean().optional(), automated: z.boolean().optional(), visibility: z.enum(["public", "private", "internal"]).optional(), file: z.string().min(24).max(24).optional(), media: z.object({url: z.string().optional(), contentType: z.string().optional()}).optional(), stats: z.object({timers: z.object({elapsedReplyTime: z.number().optional(), pricing: z.object({segments: z.number().optional(), carrierFee: z.number().optional(), baseRate: z.number().optional()}).optional()}).optional(), pricing: z.string().optional()}).optional(), retry: z.object({originalMessage: z.string().min(24).max(24).optional(), count: z.number().optional()}).optional(), terminatingStateAt: z.string().optional(), mentions: z.array(z.object({ref: z.enum(["user", "group"]).optional(), refId: z.string().min(24).max(24).optional(), mention: z.string().optional()})).optional(), recipient: z.string().min(24).max(24).optional(), recipientType: z.enum(["doctor", "staff", "patient"]).optional(), appointment: z.string().min(24).max(24).optional(), provider: z.string().min(24).max(24).optional(), appointmentType: z.string().min(24).max(24).optional(), followup: z.string().min(24).max(24).optional(), recall: z.string().min(24).max(24).optional(), referral: z.string().min(24).max(24).optional(), messageFailure: z.string().min(24).max(24).optional()}); export const getApiMessagesResponse = z.object({response: z.array(messageResponse), page: z.number().int().gte(1), size: z.number().int().gte(0)}); 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 }; /** * List messages * * GET /messages */ export const getApiMessages = async (args: GetApiMessagesArgs, options?: GetApiMessagesOptions) => { const {baseUrl = "https://api.lumahealth.io/api/v2", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.patient != null) query.append("patient", String(args.patient)) if (args.key != null) query.append("key", String(args.key)) if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args.type != null) query.append("type", String(args.type)) if (args.voiceAnsweredBy != null) query.append("voiceAnsweredBy", String(args.voiceAnsweredBy)) if (args.ref != null) query.append("ref", String(args.ref)) if (args.refId != null) query.append("refId", String(args.refId)) if (args.patientMessageTemplate != null) query.append("patientMessageTemplate", String(args.patientMessageTemplate)) if (args.outboundMessage != null) query.append("outboundMessage", String(args.outboundMessage)) if (args.status != null) query.append("status", String(args.status)) for (const item of args.externalStatus ?? []) query.append("externalStatus", String(item)) if (args.skippedStatusReason != null) query.append("skippedStatusReason", String(args.skippedStatusReason)) if (args.channel != null) query.append("channel", String(args.channel)) if (args.text != null) query.append("text", String(args.text)) if (args.classification != null) query.append("classification", String(args.classification)) if (args.secure != null) query.append("secure", String(args.secure)) if (args.automated != null) query.append("automated", String(args.automated)) if (args.visibility != null) query.append("visibility", String(args.visibility)) if (args.file != null) query.append("file", String(args.file)) if (args.recipient != null) query.append("recipient", String(args.recipient)) if (args.recipientType != null) query.append("recipientType", String(args.recipientType)) if (args.shouldForceContactWithNotifyTo != null) query.append("shouldForceContactWithNotifyTo", String(args.shouldForceContactWithNotifyTo)) if (args.appointment != null) query.append("appointment", String(args.appointment)) if (args.provider != null) query.append("provider", String(args.provider)) if (args.appointmentType != null) query.append("appointmentType", String(args.appointmentType)) if (args.followup != null) query.append("followup", String(args.followup)) if (args.recall != null) query.append("recall", String(args.recall)) if (args.referral != null) query.append("referral", String(args.referral)) if (args.messageFailure != null) query.append("messageFailure", String(args.messageFailure)) if (args.groups != null) query.append("groups", String(args.groups)) if (args.language != null) query.append("language", String(args.language)) if (args.createdBy != null) query.append("createdBy", String(args.createdBy)) if (args.updatedBy != null) query.append("updatedBy", String(args.updatedBy)) if (args.createdAt != null) query.append("createdAt", String(args.createdAt)) if (args.updatedAt != null) query.append("updatedAt", String(args.updatedAt)) if (args.page != null) query.append("page", String(args.page)) if (args.limit != null) query.append("limit", String(args.limit)) if (args._populate != null) query.append("_populate", String(args._populate)) if (args._select != null) query.append("_select", String(args._select)) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/messages${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(getApiMessagesResponse, await res.json()) };