Skip to content

Commit 2f187ea

Browse files
committed
fix(posthog): address PR review - fix pre-tx event, auth_method, paused executions, enterprise cancellation, settings double-fire
1 parent 4595e69 commit 2f187ea

File tree

5 files changed

+76
-35
lines changed

5 files changed

+76
-35
lines changed

apps/sim/app/api/workflows/route.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -250,13 +250,6 @@ export async function POST(req: NextRequest) {
250250
// Silently fail
251251
})
252252

253-
captureServerEvent(
254-
userId,
255-
'workflow_created',
256-
{ workflow_id: workflowId, workspace_id: workspaceId ?? '', name },
257-
{ groups: { workspace: workspaceId ?? '' } }
258-
)
259-
260253
const { workflowState, subBlockValues, startBlockId } = buildDefaultWorkflowArtifacts()
261254

262255
await db.transaction(async (tx) => {
@@ -282,6 +275,16 @@ export async function POST(req: NextRequest) {
282275

283276
logger.info(`[${requestId}] Successfully created workflow ${workflowId} with default blocks`)
284277

278+
captureServerEvent(
279+
userId,
280+
'workflow_created',
281+
{ workflow_id: workflowId, workspace_id: workspaceId ?? '', name },
282+
{
283+
groups: { workspace: workspaceId ?? '' },
284+
setOnce: { first_workflow_created_at: new Date().toISOString() },
285+
}
286+
)
287+
285288
recordAudit({
286289
workspaceId,
287290
actorId: userId,

apps/sim/app/workspace/[workspaceId]/settings/[section]/settings.tsx

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use client'
22

3-
import { useEffect } from 'react'
3+
import { useEffect, useRef } from 'react'
44
import dynamic from 'next/dynamic'
55
import { useSearchParams } from 'next/navigation'
66
import { usePostHog } from 'posthog-js/react'
@@ -163,6 +163,10 @@ export function SettingsPage({ section }: SettingsPageProps) {
163163
const mcpServerId = searchParams.get('mcpServerId')
164164
const { data: session, isPending: sessionLoading } = useSession()
165165
const posthog = usePostHog()
166+
const posthogRef = useRef(posthog)
167+
useEffect(() => {
168+
posthogRef.current = posthog
169+
}, [posthog])
166170

167171
const isAdminRole = session?.user?.role === 'admin'
168172
const effectiveSection =
@@ -179,8 +183,8 @@ export function SettingsPage({ section }: SettingsPageProps) {
179183

180184
useEffect(() => {
181185
if (sessionLoading) return
182-
posthog?.capture('settings_tab_viewed', { section: effectiveSection })
183-
}, [effectiveSection, sessionLoading, posthog])
186+
posthogRef.current?.capture('settings_tab_viewed', { section: effectiveSection })
187+
}, [effectiveSection, sessionLoading])
184188

185189
return (
186190
<div>

apps/sim/lib/auth/auth.ts

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
organization,
2121
} from 'better-auth/plugins'
2222
import { emailHarmony } from 'better-auth-harmony'
23-
import { and, eq, inArray, sql } from 'drizzle-orm'
23+
import { and, count, eq, inArray, sql } from 'drizzle-orm'
2424
import { headers } from 'next/headers'
2525
import Stripe from 'stripe'
2626
import {
@@ -191,13 +191,6 @@ export const auth = betterAuth({
191191
// Telemetry should not fail the operation
192192
}
193193

194-
captureServerEvent(
195-
user.id,
196-
'user_created',
197-
{ auth_method: 'email' },
198-
{ setOnce: { signup_at: new Date().toISOString() } }
199-
)
200-
201194
try {
202195
await handleNewUser(user.id)
203196
} catch (error) {
@@ -377,6 +370,34 @@ export const auth = betterAuth({
377370
})
378371
}
379372

373+
try {
374+
const [{ value: accountCount }] = await db
375+
.select({ value: count() })
376+
.from(schema.account)
377+
.where(eq(schema.account.userId, account.userId))
378+
379+
if (accountCount === 1) {
380+
const isOAuth = account.providerId !== 'credential'
381+
captureServerEvent(
382+
account.userId,
383+
'user_created',
384+
{
385+
auth_method: isOAuth ? 'oauth' : 'email',
386+
...(isOAuth ? { provider: account.providerId } : {}),
387+
},
388+
{ setOnce: { signup_at: new Date().toISOString() } }
389+
)
390+
}
391+
} catch (error) {
392+
logger.error(
393+
'[databaseHooks.account.create.after] Failed to capture user_created event',
394+
{
395+
userId: account.userId,
396+
error,
397+
}
398+
)
399+
}
400+
380401
if (account.providerId === 'salesforce') {
381402
const updates: {
382403
accessTokenExpiresAt?: Date

apps/sim/lib/billing/webhooks/subscription.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,17 @@ export async function handleSubscriptionDeleted(subscription: {
219219
organizationDeleted,
220220
membersSynced,
221221
})
222+
223+
captureServerEvent(
224+
subscription.referenceId,
225+
'subscription_cancelled',
226+
{
227+
plan: subscription.plan ?? 'unknown',
228+
reference_id: subscription.referenceId,
229+
},
230+
{ set: { plan: 'free' } }
231+
)
232+
222233
return
223234
}
224235

apps/sim/lib/workflows/executor/execute-workflow.ts

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -107,23 +107,25 @@ export async function executeWorkflow(
107107
.filter((t): t is string => typeof t === 'string')
108108
),
109109
]
110-
captureServerEvent(
111-
actorUserId,
112-
'workflow_executed',
113-
{
114-
workflow_id: workflowId,
115-
workspace_id: workspaceId,
116-
trigger_type: triggerType,
117-
success: result.success,
118-
block_count: result.logs?.length ?? 0,
119-
block_types: blockTypes.join(','),
120-
duration_ms: Date.now() - executionStartMs,
121-
},
122-
{
123-
groups: { workspace: workspaceId },
124-
setOnce: { first_execution_at: new Date().toISOString() },
125-
}
126-
)
110+
if (result.status !== 'paused') {
111+
captureServerEvent(
112+
actorUserId,
113+
'workflow_executed',
114+
{
115+
workflow_id: workflowId,
116+
workspace_id: workspaceId,
117+
trigger_type: triggerType,
118+
success: result.success,
119+
block_count: result.logs?.length ?? 0,
120+
block_types: blockTypes.join(','),
121+
duration_ms: Date.now() - executionStartMs,
122+
},
123+
{
124+
groups: { workspace: workspaceId },
125+
setOnce: { first_execution_at: new Date().toISOString() },
126+
}
127+
)
128+
}
127129

128130
if (result.status === 'paused') {
129131
if (!result.snapshotSeed) {

0 commit comments

Comments
 (0)