import {z} from 'zod' export type CreateApiApiHubspotStelorderWebhookOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const stelorderClientResult = z.object({action: z.enum(["created", "updated"]), client_id: z.number().int().nullable().optional(), payload: z.record(z.string(), z.unknown())}); export const stelorderSyncResult = z.object({hubspot_contact_id: z.string(), contact_email: z.string(), actions: z.array(z.string()).optional(), stelorder_client_id: z.number().int().nullable().optional(), stelorder_incident_id: z.number().int().nullable().optional(), stelorder_work_order_id: z.number().int().nullable().optional(), stelorder_event_id: z.number().int().nullable().optional(), google_calendar_event_id: z.string().nullable().optional()}); export const hubspotStelorderWebhookResponse = z.object({status: z.literal("ok").optional(), hubspot_contact_id: z.string().nullable().optional(), stelorder: stelorderClientResult, sync_result: stelorderSyncResult.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 }; /** * Sync Contact With Stelorder * * POST /api/hubspot/stelorder-webhook */ export const createApiApiHubspotStelorderWebhook = async (options: CreateApiApiHubspotStelorderWebhookOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/hubspot/stelorder-webhook${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(hubspotStelorderWebhookResponse, await res.json()) };