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