An open-source, faster Devin alternative
TypeScript
Signup Slack alert: say 'signed up' and list all first-touch attribution
Igor Zalutski via Computerfdc4bf7c594e
diff --git a/cloudflare-workers/api-edge/src/slack_alerts.test.ts b/cloudflare-workers/api-edge/src/slack_alerts.test.tsindex d035b772..89d4a23f 100644--- a/cloudflare-workers/api-edge/src/slack_alerts.test.ts+++ b/cloudflare-workers/api-edge/src/slack_alerts.test.ts@@ -95,10 +95,10 @@ function addOrg(VALUES (?, ?, ?, 'free', 'c', ?, 0, 0, ?)`,).run(orgID, opts.name ?? `${email}'s workspace`, `slug-${n}`, userID, opts.plan ?? "base");if (opts.attribution) {- const a = { channel: "unknown", client: "web", ...opts.attribution };+ const a = { channel: "unknown", client: "web", created_at: "0", ...opts.attribution };const cols = Object.keys(a);db.prepare(- `INSERT INTO signup_attribution (user_id, created_at, ${cols.join(", ")}) VALUES (?, 0, ${cols.map(() => "?").join(", ")})`,+ `INSERT INTO signup_attribution (user_id, ${cols.join(", ")}) VALUES (?, ${cols.map(() => "?").join(", ")})`,).run(userID, ...Object.values(a));}return orgID;@@ -120,13 +120,20 @@ function env(db: DatabaseSync, extra: Record<string, unknown> = {}) {}describe("billing-event alerts", () => {- it("posts a work-email trial start once, with its attribution", async () => {+ it("posts a work-email signup once, with its attribution", async () => {const db = schemaDB();const org = addOrg(db, "[email protected]", {name: "Acme",attribution: {channel: "google_ads",+ utm_source: "google",+ utm_medium: "cpc",utm_campaign: "launch-oct",+ utm_term: "ai <agents>",+ gclid: "abc",+ landing_path: "/pricing",+ first_seen_at: "1000000",+ created_at: "1259200",auth_method: "GitHubOAuth",plan_intent: "pro",},@@ -139,12 +146,18 @@ describe("billing-event alerts", () => {expect(posts).toEqual([{channel: "#signups",- text: "🟢 [email protected] started a trial · Acme · Google Ads / launch-oct · GitHub login · clicked Pro",+ text: [+ "🟢 [email protected] signed up · Acme · Google Ads / launch-oct · GitHub login · clicked Pro",+ "> UTM: source google, medium cpc, term ai <agents>",+ "> Ad click: Google",+ "> Landed on: /pricing",+ "> First visit: 3 days before signup",+ ].join("\n"),},]);});- it("alerts free-email trial starts and skips every internal account", async () => {+ it("alerts free-email signups and skips every internal account", async () => {const db = schemaDB();const { posts, fetchImpl } = slack();const free = addOrg(db, "[email protected]");@@ -155,7 +168,7 @@ describe("billing-event alerts", () => {}await sendSlackAlert(env(db), trialEndedAlert(staff, "days"), fetchImpl, NOW);expect(posts).toHaveLength(1);- expect(posts[0].text).toMatch(/^🟢 joe@gmail\.com started a trial/);+ expect(posts[0].text).toMatch(/^🟢 joe@gmail\.com signed up/);});it("renders each revenue event", async () => {@@ -233,7 +246,7 @@ describe("emitBillingEvent", () => {const { posts, fetchImpl } = slack();vi.stubGlobal("fetch", fetchImpl);await emitBillingEvent(env(db), "billing.trial_started", { orgId: org, userId: "u", data: { via: "web" } });- expect(posts.map((p) => p.text)).toEqual(["🟢 [email protected] started a trial · Hooli"]);+ expect(posts.map((p) => p.text)).toEqual(["🟢 [email protected] signed up · Hooli\n> No first-touch data (cookies blocked, or before attribution)"]);});});diff --git a/cloudflare-workers/api-edge/src/slack_alerts.ts b/cloudflare-workers/api-edge/src/slack_alerts.tsindex 7482166a..7d8bbcd2 100644--- a/cloudflare-workers/api-edge/src/slack_alerts.ts+++ b/cloudflare-workers/api-edge/src/slack_alerts.ts@@ -1,4 +1,4 @@-// Customer alerts in our own Slack (serverless-agents-ws 090): trial starts,+// Customer alerts in our own Slack (serverless-agents-ws 090): signups,// first agent session, conversions, trial ends, payment trouble, plan moves,// large credit purchases and teammate invites, one line each in #signups.//@@ -47,7 +47,7 @@ export interface Alert {orgId: string;// Tells repeated alerts of one kind apart; '' for once per org.key: string;- // What happened, after the email: "started a trial".+ // What happened, after the email: "signed up".what: string;// Extra context parts, after the org's own.extra?: string[];@@ -120,7 +120,8 @@ export function alertForBillingEvent(const day = today(nowMs);switch (name) {case "billing.trial_started":- return { kind: "trial_started", orgId, key: "", what: "started a trial" };+ // Every new org starts on the trial plan, so this is a signup, not a choice.+ return { kind: "trial_started", orgId, key: "", what: "signed up" };case "billing.plan_changed": {const from = planLabel(data.from);const to = planLabel(data.to);@@ -194,13 +195,26 @@ interface OrgContext {client: string | null;auth_method: string | null;plan_intent: string | null;+ utm_source: string | null;+ utm_medium: string | null;+ utm_term: string | null;+ utm_content: string | null;+ gclid: string | null;+ fbclid: string | null;+ li_fat_id: string | null;+ ref: string | null;+ landing_path: string | null;+ first_seen_at: number | null;+ signed_up_at: number | null;}async function orgContext(db: D1Database, orgId: string): Promise<OrgContext | null> {return db.prepare(`SELECT u.email, o.name AS org_name, o.usage_plan, a.channel, a.utm_campaign, a.referrer,- a.client, a.auth_method, a.plan_intent+ a.client, a.auth_method, a.plan_intent, a.utm_source, a.utm_medium, a.utm_term,+ a.utm_content, a.gclid, a.fbclid, a.li_fat_id, a.ref, a.landing_path, a.first_seen_at,+ a.created_at AS signed_up_atFROM orgs oJOIN users u ON u.id = o.owner_user_idLEFT JOIN signup_attribution a ON a.user_id = u.id@@ -210,7 +224,10 @@ async function orgContext(db: D1Database, orgId: string): Promise<OrgContext | n.first<OrgContext>();}-/** The Slack line: `🟢 [email protected] started a trial · Acme · Google Ads / launch-oct · …`. */+/**+ * The Slack line: `🟢 [email protected] signed up · Acme · Google Ads / launch-oct · …`.+ * A signup adds the rest of its attribution as quoted lines below.+ */export function alertText(alert: Alert, c: OrgContext): string {const parts: string[] = [];// A personal org keeps the signup default, which only repeats the email.@@ -224,7 +241,43 @@ export function alertText(alert: Alert, c: OrgContext): string {if (c.plan_intent) parts.push(`clicked ${planLabel(c.plan_intent)}`);}parts.push(...(alert.extra ?? []));- return [`${EMOJI[alert.kind]} ${c.email} ${alert.what}`, ...parts].join(" · ");+ const line = [`${EMOJI[alert.kind]} ${c.email} ${alert.what}`, ...parts].join(" · ");+ if (alert.kind !== "trial_started") return line;+ return [line, ...signupDetails(c).map((d) => `> ${d}`)].join("\n");+}++// Slack's escaping for text: a stored value cannot become a mention or link.+function plain(value: string): string {+ return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+}++function ago(sec: number): string {+ if (sec < 3_600) return `${Math.max(1, Math.round(sec / 60))} min`;+ if (sec < 2 * 86_400) return `${Math.round(sec / 3_600)} h`;+ return `${Math.round(sec / 86_400)} days`;+}++/** Everything signup_attribution knows beyond the headline, one fact per line. */+export function signupDetails(c: OrgContext): string[] {+ const out: string[] = [];+ if (c.client === "cli") out.push("Signed up from the CLI (no first-touch cookie)");+ else if (!c.channel || c.channel === "unknown") out.push("No first-touch data (cookies blocked, or before attribution)");+ const utm = [+ c.utm_source && `source ${plain(c.utm_source)}`,+ c.utm_medium && `medium ${plain(c.utm_medium)}`,+ c.utm_term && `term ${plain(c.utm_term)}`,+ c.utm_content && `content ${plain(c.utm_content)}`,+ ].filter(Boolean);+ if (utm.length) out.push(`UTM: ${utm.join(", ")}`);+ const clicks = [c.gclid && "Google", c.fbclid && "Meta", c.li_fat_id && "LinkedIn"].filter(Boolean);+ if (clicks.length) out.push(`Ad click: ${clicks.join(", ")}`);+ if (c.ref) out.push(`Ref: ${plain(c.ref)}`);+ if (c.referrer) out.push(`Referrer: ${plain(c.referrer)}`);+ if (c.landing_path) out.push(`Landed on: ${plain(c.landing_path)}`);+ if (c.first_seen_at != null && c.signed_up_at != null && c.signed_up_at >= c.first_seen_at) {+ out.push(`First visit: ${ago(c.signed_up_at - c.first_seen_at)} before signup`);+ }+ return out;}function sourceLabel(c: OrgContext): string | null {