Skip to content

Commit

Permalink
馃搱 (posthog) Send user last login event
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Mar 4, 2024
1 parent 8846cdb commit 434b067
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
10 changes: 9 additions & 1 deletion apps/builder/src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import got from 'got'
import { env } from '@typebot.io/env'
import * as Sentry from '@sentry/nextjs'
import { getIp } from '@typebot.io/lib/getIp'
import { trackEvents } from '@typebot.io/lib/telemetry/trackEvents'

const providers: Provider[] = []

Expand Down Expand Up @@ -218,11 +219,18 @@ const updateLastActivityDate = async (user: User) => {
first.getMonth() === second.getMonth() &&
first.getDate() === second.getDate()

if (!datesAreOnSameDay(user.lastActivityAt, new Date()))
if (!datesAreOnSameDay(user.lastActivityAt, new Date())) {
await prisma.user.updateMany({
where: { id: user.id },
data: { lastActivityAt: new Date() },
})
await trackEvents([
{
name: 'User logged in',
userId: user.id,
},
])
}
}

const getUserGroups = async (account: Account): Promise<string[]> => {
Expand Down
6 changes: 6 additions & 0 deletions packages/lib/telemetry/trackEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ export const trackEvents = async (events: TelemetryEvent[]) => {
properties:
event.name === 'User updated'
? { $set: event.data }
: event.name === 'User logged in'
? {
$set: {
lastActivityAt: new Date().toISOString(),
},
}
: 'data' in event
? event.data
: undefined,
Expand Down
7 changes: 7 additions & 0 deletions packages/schemas/features/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ const userCreatedEventSchema = userEvent.merge(
})
)

const userLoggedInEventSchema = userEvent.merge(
z.object({
name: z.literal('User logged in'),
})
)

const userUpdatedEventSchema = userEvent.merge(
z.object({
name: z.literal('User updated'),
Expand Down Expand Up @@ -173,6 +179,7 @@ export const clientSideEvents = [removedBrandingEventSchema] as const
export const eventSchema = z.discriminatedUnion('name', [
workspaceCreatedEventSchema,
userCreatedEventSchema,
userLoggedInEventSchema,
typebotCreatedEventSchema,
publishedTypebotEventSchema,
subscriptionUpdatedEventSchema,
Expand Down

0 comments on commit 434b067

Please sign in to comment.