|
| 1 | +import { z } from "zod"; |
| 2 | +import { env } from "~/env.server"; |
| 3 | +import { logger } from "./logger.server"; |
| 4 | + |
| 5 | +// Syncs new orgs/users into Attio (workspaces/users objects) at signup, via the |
| 6 | +// common worker so a slow Attio never blocks signup. Ongoing field updates are |
| 7 | +// handled by the scheduled sync, not here. No-op without ATTIO_API_KEY. |
| 8 | + |
| 9 | +const ATTIO_API = "https://api.attio.com/v2"; |
| 10 | +const IS_TEST = env.APP_ENV !== "production"; |
| 11 | + |
| 12 | +export const AttioWorkspaceSyncSchema = z.object({ |
| 13 | + orgId: z.string(), |
| 14 | + title: z.string(), |
| 15 | + slug: z.string(), |
| 16 | + companySize: z.string().nullish(), |
| 17 | + createdAt: z.coerce.date(), |
| 18 | +}); |
| 19 | +export type AttioWorkspaceSync = z.infer<typeof AttioWorkspaceSyncSchema>; |
| 20 | + |
| 21 | +export const AttioUserSyncSchema = z.object({ |
| 22 | + userId: z.string(), |
| 23 | + email: z.string(), |
| 24 | + referralSource: z.string().nullish(), |
| 25 | + marketingEmails: z.boolean(), |
| 26 | + createdAt: z.coerce.date(), |
| 27 | +}); |
| 28 | +export type AttioUserSync = z.infer<typeof AttioUserSyncSchema>; |
| 29 | + |
| 30 | +class AttioClient { |
| 31 | + constructor(private readonly apiKey: string) {} |
| 32 | + |
| 33 | + // Create-or-update by unique attribute; throws on failure so the worker retries. |
| 34 | + async #assert(object: string, matchingAttribute: string, values: Record<string, unknown>) { |
| 35 | + const url = `${ATTIO_API}/objects/${object}/records?matching_attribute=${matchingAttribute}`; |
| 36 | + const response = await fetch(url, { |
| 37 | + method: "PUT", |
| 38 | + headers: { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" }, |
| 39 | + body: JSON.stringify({ data: { values } }), |
| 40 | + }); |
| 41 | + |
| 42 | + if (!response.ok) { |
| 43 | + const body = await response.text(); |
| 44 | + logger.error("Attio assert failed", { object, matchingAttribute, status: response.status, body }); |
| 45 | + throw new Error(`Attio assert ${object} failed with status ${response.status}`); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + async upsertWorkspace(payload: AttioWorkspaceSync) { |
| 50 | + await this.#assert("workspaces", "workspace_id", { |
| 51 | + workspace_id: payload.orgId, |
| 52 | + name: payload.title, |
| 53 | + org_slug: payload.slug, |
| 54 | + company_size: payload.companySize ?? undefined, |
| 55 | + signup_date: toDate(payload.createdAt), |
| 56 | + plan: "Free", |
| 57 | + account_status: "Active", |
| 58 | + is_test: IS_TEST, |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + async upsertUser(payload: AttioUserSync) { |
| 63 | + await this.#assert("users", "user_id", { |
| 64 | + user_id: payload.userId, |
| 65 | + primary_email_address: payload.email, |
| 66 | + marketing_opt_in: payload.marketingEmails, |
| 67 | + referral_source: payload.referralSource ?? undefined, |
| 68 | + signup_date: toDate(payload.createdAt), |
| 69 | + is_test: IS_TEST, |
| 70 | + }); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// Attio `date` attributes want a bare YYYY-MM-DD value. |
| 75 | +function toDate(date: Date): string { |
| 76 | + return date.toISOString().slice(0, 10); |
| 77 | +} |
| 78 | + |
| 79 | +export const attioClient = env.ATTIO_API_KEY ? new AttioClient(env.ATTIO_API_KEY) : null; |
| 80 | + |
| 81 | +export async function enqueueAttioWorkspaceSync(payload: AttioWorkspaceSync) { |
| 82 | + if (!attioClient) return; |
| 83 | + try { |
| 84 | + // Lazy import to avoid a circular dependency with commonWorker (which imports this module's schemas). |
| 85 | + const { commonWorker } = await import("~/v3/commonWorker.server"); |
| 86 | + await commonWorker.enqueue({ id: `attio:workspace:${payload.orgId}`, job: "attio.syncWorkspace", payload }); |
| 87 | + } catch (error) { |
| 88 | + logger.error("Failed to enqueue Attio workspace sync", { orgId: payload.orgId, error }); |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +export async function enqueueAttioUserSync(payload: AttioUserSync) { |
| 93 | + if (!attioClient) return; |
| 94 | + try { |
| 95 | + const { commonWorker } = await import("~/v3/commonWorker.server"); |
| 96 | + await commonWorker.enqueue({ id: `attio:user:${payload.userId}`, job: "attio.syncUser", payload }); |
| 97 | + } catch (error) { |
| 98 | + logger.error("Failed to enqueue Attio user sync", { userId: payload.userId, error }); |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +export async function runAttioWorkspaceSync(payload: AttioWorkspaceSync) { |
| 103 | + if (!attioClient) return; |
| 104 | + await attioClient.upsertWorkspace(payload); |
| 105 | +} |
| 106 | + |
| 107 | +export async function runAttioUserSync(payload: AttioUserSync) { |
| 108 | + if (!attioClient) return; |
| 109 | + await attioClient.upsertUser(payload); |
| 110 | +} |
0 commit comments