2024-02-01 14:19:24 +01:00
|
|
|
import { env } from '@typebot.io/env'
|
|
|
|
import { TelemetryEvent } from '@typebot.io/schemas/features/telemetry'
|
|
|
|
import { PostHog } from 'posthog-node'
|
2024-04-05 09:01:16 +02:00
|
|
|
import ky from 'ky'
|
2024-02-01 14:19:24 +01:00
|
|
|
|
|
|
|
export const trackEvents = async (events: TelemetryEvent[]) => {
|
|
|
|
if (!env.NEXT_PUBLIC_POSTHOG_KEY) return
|
|
|
|
const client = new PostHog(env.NEXT_PUBLIC_POSTHOG_KEY, {
|
|
|
|
host: env.NEXT_PUBLIC_POSTHOG_HOST,
|
|
|
|
})
|
|
|
|
|
|
|
|
events.forEach(async (event) => {
|
|
|
|
if (event.name === 'User created') {
|
|
|
|
client.identify({
|
|
|
|
distinctId: event.userId,
|
|
|
|
properties: event.data,
|
|
|
|
})
|
|
|
|
if (env.USER_CREATED_WEBHOOK_URL) {
|
2024-02-03 12:38:09 +01:00
|
|
|
try {
|
2024-04-05 09:01:16 +02:00
|
|
|
await ky.post(env.USER_CREATED_WEBHOOK_URL, {
|
2024-02-03 12:38:09 +01:00
|
|
|
json: {
|
|
|
|
email: event.data.email,
|
|
|
|
name: event.data.name ? event.data.name.split(' ')[0] : undefined,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
} catch (e) {
|
|
|
|
console.error('Failed to call user created webhook', e)
|
|
|
|
}
|
2024-02-01 14:19:24 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if (
|
|
|
|
event.name === 'Workspace created' ||
|
|
|
|
event.name === 'Subscription updated'
|
|
|
|
)
|
|
|
|
client.groupIdentify({
|
|
|
|
groupType: 'workspace',
|
|
|
|
groupKey: event.workspaceId,
|
|
|
|
properties: event.data,
|
|
|
|
})
|
|
|
|
if (event.name === 'Typebot created' || event.name === 'Typebot published')
|
|
|
|
client.groupIdentify({
|
|
|
|
groupType: 'typebot',
|
|
|
|
groupKey: event.typebotId,
|
|
|
|
properties: { name: event.data.name },
|
|
|
|
})
|
|
|
|
const groups: { workspace?: string; typebot?: string } = {}
|
|
|
|
if ('workspaceId' in event) groups['workspace'] = event.workspaceId
|
|
|
|
if ('typebotId' in event) groups['typebot'] = event.typebotId
|
|
|
|
client.capture({
|
|
|
|
distinctId: event.userId,
|
|
|
|
event: event.name,
|
2024-02-02 11:58:32 +01:00
|
|
|
properties:
|
|
|
|
event.name === 'User updated'
|
|
|
|
? { $set: event.data }
|
2024-03-04 10:04:48 +01:00
|
|
|
: event.name === 'User logged in'
|
|
|
|
? {
|
|
|
|
$set: {
|
|
|
|
lastActivityAt: new Date().toISOString(),
|
|
|
|
},
|
|
|
|
}
|
2024-02-02 11:58:32 +01:00
|
|
|
: 'data' in event
|
|
|
|
? event.data
|
|
|
|
: undefined,
|
2024-02-01 14:19:24 +01:00
|
|
|
groups,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
await client.shutdownAsync()
|
|
|
|
}
|