Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(analytics): group PostHog events by team (#8401)

Chaitanya Agarwal2955a41f6d0d
diff --git a/apps/web/src/lib/analytics/analytics.test.ts b/apps/web/src/lib/analytics/analytics.test.ts
index f9be05ec94..4d9cb1cf4c 100644
--- a/apps/web/src/lib/analytics/analytics.test.ts
+++ b/apps/web/src/lib/analytics/analytics.test.ts
@@ -6,6 +6,11 @@ const mocks = vi.hoisted(() => ({
capture: vi.fn(),
identify: vi.fn(),
init: vi.fn(),
+ group: vi.fn(),
+ resetGroups: vi.fn(),
+ groups: {} as Record<string, string>,
+ unregister: vi.fn(),
+ reset: vi.fn(),
gtag: vi.fn(),
fbq: vi.fn(),
}));
@@ -26,6 +31,11 @@ vi.mock('posthog-js', () => ({
capture = mocks.capture;
identify = mocks.identify;
init = mocks.init;
+ group = mocks.group;
+ resetGroups = mocks.resetGroups;
+ getGroups = () => mocks.groups;
+ unregister = mocks.unregister;
+ reset = mocks.reset;
},
}));
@@ -38,6 +48,7 @@ beforeEach(() => {
vi.stubGlobal('fbq', mocks.fbq);
mocks.platform = 'web';
mocks.touch = false;
+ mocks.groups = {};
});
afterEach(() => {
@@ -224,3 +235,46 @@ describe('PostHog exception frames', () => {
).toEqual(['https://macro.com/app/app-gifhAVYj.js']);
});
});
+
+describe('PostHog team group', () => {
+ const team = {
+ id: '00000000-0000-0000-0000-000000000001',
+ name: 'Acme',
+ enterprise: false,
+ };
+
+ it('groups events by team, re-sending only when the team changes', async () => {
+ const { analytics } = await import('./analytics');
+
+ analytics.setTeamGroup(team);
+ analytics.setTeamGroup(team);
+ analytics.setTeamGroup({ ...team, name: 'Acme Inc' });
+
+ expect(mocks.group.mock.calls).toEqual([
+ ['team', team.id, { name: 'Acme', enterprise: false }],
+ ['team', team.id, { name: 'Acme Inc', enterprise: false }],
+ ]);
+ });
+
+ it('sets the group again after logout resets PostHog', async () => {
+ const { analytics } = await import('./analytics');
+
+ analytics.setTeamGroup(team);
+ analytics.reset();
+ analytics.setTeamGroup(team);
+
+ expect(mocks.reset).toHaveBeenCalledTimes(1);
+ expect(mocks.group).toHaveBeenCalledTimes(2);
+ });
+
+ it('clears the team group only when one is set', async () => {
+ const { analytics } = await import('./analytics');
+
+ analytics.clearTeamGroup();
+ expect(mocks.resetGroups).not.toHaveBeenCalled();
+
+ mocks.groups = { team: team.id };
+ analytics.clearTeamGroup();
+ expect(mocks.resetGroups).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/src/lib/analytics/analytics.ts b/apps/web/src/lib/analytics/analytics.ts
index daee6953e5..40ee3a6267 100644
--- a/apps/web/src/lib/analytics/analytics.ts
+++ b/apps/web/src/lib/analytics/analytics.ts
@@ -15,6 +15,7 @@ import {
redactCallLinkTokens,
} from '@core/util/telemetryUrl';
import { getWebOrigin } from '@core/util/webOrigin';
+import type { Team } from '@service-auth/generated/schemas/team';
import { type CaptureOptions, PostHog } from 'posthog-js';
import { match } from 'ts-pattern';
import { isIgnorableException, rewriteNativeFrameUrls } from './exceptionList';
@@ -35,6 +36,8 @@ const DEVICE_PROPERTY = 'macro_device' as const;
const ENVIRONMENT_PROPERTY = 'macro_environment' as const;
const PLAN_TIER_AT_EVENT_PROPERTY = 'plan_tier_at_event' as const;
const HAS_PAID_ACCESS_AT_EVENT_PROPERTY = 'has_paid_access_at_event' as const;
+/** PostHog group type for team analytics; server events send the same key. */
+const TEAM_GROUP_TYPE = 'team' as const;
function getEnvironment(): 'dev' | 'prod' | 'unknown' {
if (PROD_MODE_ENV) return 'prod';
@@ -70,6 +73,8 @@ type TrackFn = <E extends EventName>(
options?: TrackOptions
) => void;
+type TeamGroupInfo = Pick<Team, 'id' | 'name' | 'enterprise'>;
+
interface UserIdentifyInfo {
email: string;
os: string;
@@ -344,12 +349,50 @@ const createAnalytics = () => {
}
};
+ // `group` with properties captures a `$groupidentify` event, so only send
+ // it when the team or its properties change, not on every team refetch.
+ let syncedTeamGroupKey: string | undefined;
+
+ const setTeamGroup = (team: TeamGroupInfo) => {
+ if (disabled) return;
+
+ const key = `${team.id}:${team.name}:${team.enterprise}`;
+ if (syncedTeamGroupKey === key) return;
+
+ try {
+ posthog.group(TEAM_GROUP_TYPE, team.id, {
+ name: team.name,
+ enterprise: team.enterprise,
+ });
+ syncedTeamGroupKey = key;
+ } catch (e) {
+ console.error('[Analytics] Failed to set team group:', e);
+ }
+ };
+
+ const clearTeamGroup = () => {
+ if (disabled) return;
+
+ syncedTeamGroupKey = undefined;
+ try {
+ // The group persists across reloads; clear it only when one is set,
+ // since `resetGroups` also reloads feature flags.
+ if (posthog.getGroups()[TEAM_GROUP_TYPE] === undefined) return;
+ posthog.resetGroups();
+ } catch (e) {
+ console.error('[Analytics] Failed to clear team group:', e);
+ }
+ };
+
const reset = () => {
if (disabled) return;
try {
gtag('config', GA_ID, { user_id: undefined });
+ // `posthog.reset()` clears the persisted groups.
+ syncedTeamGroupKey = undefined;
+
posthog.unregister(PLAN_TIER_AT_EVENT_PROPERTY);
posthog.unregister(HAS_PAID_ACCESS_AT_EVENT_PROPERTY);
posthog.reset();
@@ -408,6 +451,8 @@ const createAnalytics = () => {
trackGoogleConversion,
identify,
setPlanProperties,
+ setTeamGroup,
+ clearTeamGroup,
reset,
pageView,
};
@@ -427,6 +472,10 @@ export type AnalyticsInterface = {
) => void;
identify: (userID: string, info: Partial<UserIdentifyInfo>) => void;
setPlanProperties: (licenseStatus: string | undefined) => void;
+ /** Associates this user's events with their team (PostHog group analytics). */
+ setTeamGroup: (team: TeamGroupInfo) => void;
+ /** Detaches events from any team, e.g. after leaving it. */
+ clearTeamGroup: () => void;
reset: () => void;
pageView: (pageTitle: string, opts?: PageViewOptions) => void;
};
diff --git a/apps/web/src/lib/core/context/team.tsx b/apps/web/src/lib/core/context/team.tsx
index fbbae4f858..2241e333f0 100644
--- a/apps/web/src/lib/core/context/team.tsx
+++ b/apps/web/src/lib/core/context/team.tsx
@@ -1,5 +1,6 @@
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useCurrentTeamQuery } from '@queries/team/teams';
-import { type Accessor, createMemo } from 'solid-js';
+import { type Accessor, createEffect, createMemo } from 'solid-js';
import { createAssertedContextProvider } from './createContext';
export const MACRO_TEAM_SLUG = 'MACRO';
@@ -10,6 +11,7 @@ type TeamContextValue = {
export const [TeamContextProvider, useTeamContext] =
createAssertedContextProvider('TeamContext', (): TeamContextValue => {
+ const analytics = useAnalytics();
const currentTeam = useCurrentTeamQuery();
// Guarded: `data` suspends while the team query waits on sign-in, and this
// provider wraps the whole app.
@@ -18,6 +20,15 @@ export const [TeamContextProvider, useTeamContext] =
currentTeam.isSuccess && currentTeam.data?.team.slug === MACRO_TEAM_SLUG
);
+ // Keep the PostHog team group in step with membership: creating, joining,
+ // leaving, or renaming a team all refetch this query.
+ createEffect(() => {
+ if (!currentTeam.isSuccess) return;
+ const team = currentTeam.data?.team;
+ if (team) analytics.setTeamGroup(team);
+ else analytics.clearTeamGroup();
+ });
+
return {
isMacroTeam,
};
diff --git a/crates/teams/src/outbound/team_analytics.rs b/crates/teams/src/outbound/team_analytics.rs
index 0450f6343e..ea401f03ac 100644
--- a/crates/teams/src/outbound/team_analytics.rs
+++ b/crates/teams/src/outbound/team_analytics.rs
@@ -23,9 +23,18 @@ impl AnalyticsClientTeamAnalytics {
}
}
+/// PostHog group analytics: attributes the event to the team group, keyed the
+/// same way the web app's `posthog.group('team', ...)` call keys it.
+#[derive(Debug, Eq, PartialEq, Serialize)]
+struct TeamAnalyticsGroups {
+ team: uuid::Uuid,
+}
+
#[derive(Debug, Eq, PartialEq, Serialize)]
struct TeamAnalyticsProperties {
team_id: uuid::Uuid,
+ #[serde(rename = "$groups")]
+ groups: TeamAnalyticsGroups,
#[serde(skip_serializing_if = "Option::is_none")]
team_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -46,6 +55,7 @@ impl TeamAnalyticsProperties {
fn new(team_id: uuid::Uuid) -> Self {
Self {
team_id,
+ groups: TeamAnalyticsGroups { team: team_id },
team_name: None,
team_invite_id: None,
owner_id: None,
diff --git a/crates/teams/src/outbound/team_analytics/test.rs b/crates/teams/src/outbound/team_analytics/test.rs
index a0594617fb..a556081e74 100644
--- a/crates/teams/src/outbound/team_analytics/test.rs
+++ b/crates/teams/src/outbound/team_analytics/test.rs
@@ -53,7 +53,7 @@ fn maps_team_events_to_expected_posthog_names() {
}
#[test]
-fn mapped_team_events_include_team_id_in_properties() {
+fn mapped_team_events_include_team_id_and_team_group() {
let team_id = uuid::Uuid::from_u128(1).to_string();
for event in test_events() {
@@ -61,6 +61,7 @@ fn mapped_team_events_include_team_id_in_properties() {
let properties = serde_json::to_value(&posthog_event.properties).unwrap();
assert_eq!(properties["team_id"], team_id);
+ assert_eq!(properties["$groups"], json!({ "team": team_id }));
}
}
@@ -79,6 +80,7 @@ fn maps_team_created_context() {
properties,
json!({
"team_id": uuid::Uuid::from_u128(1),
+ "$groups": { "team": uuid::Uuid::from_u128(1) },
"team_name": "Acme",
"owner_id": "macro|[email protected]",
})
@@ -101,6 +103,7 @@ fn maps_team_invited_context() {
properties,
json!({
"team_id": uuid::Uuid::from_u128(1),
+ "$groups": { "team": uuid::Uuid::from_u128(1) },
"team_name": "Acme",
"team_invite_id": uuid::Uuid::from_u128(2),
"inviter_id": "macro|[email protected]",
@@ -124,6 +127,7 @@ fn maps_team_joined_context() {
properties,
json!({
"team_id": uuid::Uuid::from_u128(1),
+ "$groups": { "team": uuid::Uuid::from_u128(1) },
"team_invite_id": uuid::Uuid::from_u128(2),
"member_id": "macro|[email protected]",
"role": "member",
@@ -146,6 +150,7 @@ fn maps_team_left_context() {
properties,
json!({
"team_id": uuid::Uuid::from_u128(1),
+ "$groups": { "team": uuid::Uuid::from_u128(1) },
"member_id": "macro|[email protected]",
"removed_by_id": "macro|[email protected]",
"role": "admin",
diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
index 285d4cb24b..03563800b4 100644
--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook.rs
@@ -384,6 +384,7 @@ async fn handle_payment_event(
currency: subscription_currency,
status: subscription_status.to_string(),
is_new: false,
+ team_id: Some(team_id),
},
)
.await;
@@ -603,6 +604,7 @@ async fn handle_customer_subscription_event(
currency: subscription_currency,
status: subscription_status.to_string(),
is_new: is_new_subscription,
+ team_id: Some(team_id),
},
)
.await;
@@ -729,6 +731,7 @@ async fn handle_customer_subscription_event(
currency: subscription_currency,
status: subscription_status.to_string(),
is_new: is_new_subscription,
+ team_id: None,
},
);
@@ -892,6 +895,24 @@ struct SubscriptionEvent {
currency: String,
}
+/// PostHog properties for a subscription event. GA and Meta get the bare
+/// [`SubscriptionEvent`]; only PostHog receives the team and its group.
+#[derive(Debug, Serialize)]
+struct PostHogSubscriptionEvent<'a> {
+ #[serde(flatten)]
+ event: &'a SubscriptionEvent,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ team_id: Option<uuid::Uuid>,
+ #[serde(rename = "$groups", skip_serializing_if = "Option::is_none")]
+ groups: Option<PostHogTeamGroup>,
+}
+
+/// Attributes the event to the team in PostHog group analytics.
+#[derive(Debug, Serialize)]
+struct PostHogTeamGroup {
+ team: uuid::Uuid,
+}
+
#[derive(Debug, Clone)]
struct SubscriptionTrackingData {
ga_client_id: Option<String>,
@@ -902,6 +923,8 @@ struct SubscriptionTrackingData {
currency: Option<String>,
status: String,
is_new: bool,
+ /// Set for team subscriptions (the `team_id` subscription metadata).
+ team_id: Option<uuid::Uuid>,
}
/// Tracks a Stripe subscription event to GA and Meta (fire-and-forget).
@@ -950,6 +973,11 @@ fn track_stripe_subscription(
..MetaUserData::default()
};
let event_id = Some(subscription_id.as_str());
+ let posthog_event = PostHogSubscriptionEvent {
+ event: &event,
+ team_id: data.team_id,
+ groups: data.team_id.map(|team| PostHogTeamGroup { team }),
+ };
// PostHog distinct id must be the "macro|{email}" id the app
// identifies with; a bare email lands events on orphaned person
// profiles disconnected from product usage. This only links to the
@@ -992,7 +1020,7 @@ fn track_stripe_subscription(
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track Meta purchase event"));
let _ = client
- .track_posthog(&posthog_distinct_id, "subscription_created", &event)
+ .track_posthog(&posthog_distinct_id, "subscription_created", &posthog_event)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track PostHog subscription_created event"));
}
@@ -1017,7 +1045,7 @@ fn track_stripe_subscription(
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track Meta cancel event"));
let _ = client
- .track_posthog(&posthog_distinct_id, "subscription_canceled", &event)
+ .track_posthog(&posthog_distinct_id, "subscription_canceled", &posthog_event)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track PostHog subscription_canceled event"));
}
diff --git a/services/authentication_service/src/api/webhooks/user/stripe_webhook/test.rs b/services/authentication_service/src/api/webhooks/user/stripe_webhook/test.rs
index 37abd1e9a1..c04fec26e7 100644
--- a/services/authentication_service/src/api/webhooks/user/stripe_webhook/test.rs
+++ b/services/authentication_service/src/api/webhooks/user/stripe_webhook/test.rs
@@ -1,7 +1,12 @@
use roles_and_permissions::domain::model::SubscriptionStatus;
use stripe_webhook::EventType;
-use super::{PaymentEventOutcome, is_active_subscription_except_current};
+use serde_json::json;
+
+use super::{
+ PaymentEventOutcome, PostHogSubscriptionEvent, PostHogTeamGroup, SubscriptionEvent,
+ is_active_subscription_except_current,
+};
#[test]
fn invoice_payment_failed_maps_to_revoke_outcome() {
@@ -74,3 +79,56 @@ fn invoice_payment_active_subscription_check_excludes_current_subscription() {
current_subscription_id,
));
}
+
+#[test]
+fn posthog_team_subscription_event_carries_team_id_and_group() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let event = SubscriptionEvent {
+ transaction_id: "sub_123".to_string(),
+ value: 20.0,
+ currency: "USD".to_string(),
+ };
+
+ let properties = serde_json::to_value(PostHogSubscriptionEvent {
+ event: &event,
+ team_id: Some(team_id),
+ groups: Some(PostHogTeamGroup { team: team_id }),
+ })
+ .unwrap();
+
+ assert_eq!(
+ properties,
+ json!({
+ "transaction_id": "sub_123",
+ "value": 20.0,
+ "currency": "USD",
+ "team_id": "00000000-0000-0000-0000-000000000001",
+ "$groups": { "team": "00000000-0000-0000-0000-000000000001" },
+ })
+ );
+}
+
+#[test]
+fn posthog_personal_subscription_event_has_no_team() {
+ let event = SubscriptionEvent {
+ transaction_id: "sub_123".to_string(),
+ value: 20.0,
+ currency: "USD".to_string(),
+ };
+
+ let properties = serde_json::to_value(PostHogSubscriptionEvent {
+ event: &event,
+ team_id: None,
+ groups: None,
+ })
+ .unwrap();
+
+ assert_eq!(
+ properties,
+ json!({
+ "transaction_id": "sub_123",
+ "value": 20.0,
+ "currency": "USD",
+ })
+ );
+}