Skip to content

Commit

Permalink
feat(analytics): track metrics for apps and groups as for users (#2627)
Browse files Browse the repository at this point in the history
  • Loading branch information
poolsar42 committed Aug 22, 2023
1 parent 3f15d98 commit 71aca00
Show file tree
Hide file tree
Showing 22 changed files with 182 additions and 169 deletions.
1 change: 0 additions & 1 deletion apps/console/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,6 @@ export default function App() {
api_host: loaderData.ENV.POSTHOG_PROXY_HOST,
autocapture: false,
})

posthog?.identify(identityURN)
} catch (ex) {
console.error(ex)
Expand Down
17 changes: 1 addition & 16 deletions apps/console/app/routes/__layout/billing/webhook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -208,22 +208,7 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
)

await createAnalyticsEvent({
eventName: 'purchase',
apiKey: context.env.POSTHOG_API_KEY,
distinctId: customerDataSuccess.metadata.identityURN,
properties: {
plans: purchasedItems.map((item) => ({
quantity: item.quantity,
name: products.find(
(product) => product?.id === item?.productID
)!.name,
type: ServicePlanType.PRO,
})),
},
})

await createAnalyticsEvent({
eventName: 'purchase',
eventName: 'identity_purchased_entitlement',
apiKey: context.env.POSTHOG_API_KEY,
distinctId: customerDataSuccess.metadata.identityURN,
properties: {
Expand Down
28 changes: 5 additions & 23 deletions apps/console/app/routes/__layout/spuorg/$groupID/invite.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import { generateTraceContextHeaders } from '@proofzero/platform-middleware/trace'
import { getRollupReqFunctionErrorWrapper } from '@proofzero/utils/errors'
import { ActionFunction, json } from '@remix-run/cloudflare'
import { type ActionFunction, json } from '@remix-run/cloudflare'
import { requireJWT } from '~/utilities/session.server'
import createCoreClient from '@proofzero/platform-clients/core'
import {
getAuthzHeaderConditionallyFromToken,
parseJwt,
} from '@proofzero/utils'
import { getAuthzHeaderConditionallyFromToken } from '@proofzero/utils'
import { BadRequestError } from '@proofzero/errors'
import {
import type {
CryptoAccountType,
EmailAccountType,
OAuthAccountType,
} from '@proofzero/types/account'
import {
IdentityGroupURN,
type IdentityGroupURN,
IdentityGroupURNSpace,
} from '@proofzero/urns/identity-group'
import { createAnalyticsEvent } from '@proofzero/utils/analytics'
import { type IdentityURN } from '@proofzero/urns/identity'

export type InviteRes = {
inviteCode: string
}
Expand All @@ -31,8 +27,6 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
) as IdentityGroupURN

const jwt = await requireJWT(request, context.env)
const parsedJwt = parseJwt(jwt!)
const identityURN = parsedJwt.sub as IdentityURN

const fd = await request.formData()
const accountType = fd.get('accountType') as
Expand Down Expand Up @@ -64,18 +58,6 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
identityGroupURN: groupURN,
})

await createAnalyticsEvent({
eventName: 'member_invited_to_group',
distinctId: identityURN,
apiKey: context.env.POSTHOG_API_KEY,
groups: {
group: groupID,
},
properties: {
groupID: groupID,
},
})

return json({
inviteCode,
} as InviteRes)
Expand Down
17 changes: 1 addition & 16 deletions apps/console/app/routes/apps/delete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,14 @@ import { redirect } from '@remix-run/cloudflare'
import type { ActionFunction } from '@remix-run/cloudflare'
import createCoreClient from '@proofzero/platform-clients/core'
import { requireJWT } from '~/utilities/session.server'
import {
getAuthzHeaderConditionallyFromToken,
parseJwt,
} from '@proofzero/utils'
import { getAuthzHeaderConditionallyFromToken } from '@proofzero/utils'
import { generateTraceContextHeaders } from '@proofzero/platform-middleware/trace'
import {
JsonError,
getErrorCause,
getRollupReqFunctionErrorWrapper,
} from '@proofzero/utils/errors'
import { BadRequestError, InternalServerError } from '@proofzero/errors'
import { createAnalyticsEvent } from '@proofzero/utils/analytics'
import { type IdentityURN } from '@proofzero/urns/identity'

export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
async ({ request, context }) => {
Expand All @@ -25,23 +20,13 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
throw new BadRequestError({ message: 'Client ID is required' })

const jwt = await requireJWT(request, context.env)
const parsedJwt = parseJwt(jwt as string)
const identityURN = parsedJwt.sub as IdentityURN

const coreClient = createCoreClient(context.env.Core, {
...getAuthzHeaderConditionallyFromToken(jwt),
...generateTraceContextHeaders(context.traceSpan),
})
try {
await coreClient.starbase.deleteApp.mutate({ clientId })
await createAnalyticsEvent({
apiKey: context.env.POSTHOG_API_KEY,
eventName: 'app_deleted',
distinctId: identityURN,
properties: {
client_id: clientId,
},
})
return redirect('/')
} catch (error) {
const cause = getErrorCause(error)
Expand Down
6 changes: 3 additions & 3 deletions apps/console/app/routes/apps/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,14 @@ export default function CreateNewApp() {
<SiteHeader avatarUrl={avatarUrl} />

<section
className={`${open
className={`${
open
? 'max-lg:opacity-50\
max-lg:overflow-hidden\
max-lg:h-[calc(100dvh-80px)]\
min-h-[636px]'
: 'h-full '
} py-9 sm:mx-11 lg:flex lg:justify-center`}
} py-9 sm:mx-11 lg:flex lg:justify-center`}
>
<div
className={`lg:w-[60%] relative rounded-lg px-4 pt-5 pb-4
Expand Down Expand Up @@ -114,7 +115,6 @@ export default function CreateNewApp() {
? 'flex items-center justify-between transition'
: ''
}
onClick={() => posthog?.capture('new_app_created')}
disabled={isSubmitting}
>
{isSubmitting && (
Expand Down
3 changes: 0 additions & 3 deletions apps/passport/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,6 @@ export default function App() {
autocapture: false,
})
posthog?.reset()
posthog?.group('app', browserEnv?.appProps?.clientId, {
name: browserEnv?.appProps?.name,
})
} catch (ex) {
console.error(ex)
}
Expand Down
22 changes: 4 additions & 18 deletions apps/passport/app/routes/authorize.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ import { Helmet } from 'react-helmet'
import { getRGBColor, getTextColor } from '@proofzero/design-system/src/helpers'
import { AccountURNSpace } from '@proofzero/urns/account'
import type { DropdownSelectListItem } from '@proofzero/design-system/src/atoms/dropdown/DropdownSelectList'
import { createAnalyticsEvent } from '@proofzero/utils/analytics'

export type UserProfile = {
displayName: string
Expand Down Expand Up @@ -374,19 +373,6 @@ export const action: ActionFunction = async ({ request, context }) => {
throw json({ message: 'Failed to authorize' }, 400)
}

await createAnalyticsEvent({
eventName: 'app_authorized',
distinctId: identityURN,
apiKey: context.env.POSTHOG_API_KEY,
groups: {
app: clientId,
},
properties: {
clientId: clientId,
scope: scope,
},
})

const redirectParams = new URLSearchParams({
code: authorizeRes.code,
state: authorizeRes.state,
Expand Down Expand Up @@ -444,8 +430,8 @@ export default function Authorize() {
return [AuthorizationControlSelection.ALL]
} else {
return connectedAccounts?.length
? connectedAccounts.filter(
(acc) => persona.connected_accounts?.includes(acc.value)
? connectedAccounts.filter((acc) =>
persona.connected_accounts?.includes(acc.value)
)
: []
}
Expand All @@ -457,8 +443,8 @@ export default function Authorize() {
return [AuthorizationControlSelection.ALL]
} else {
return connectedSmartContractWallets?.length
? connectedSmartContractWallets.filter(
(acc) => persona.erc_4337?.includes(acc.value)
? connectedSmartContractWallets.filter((acc) =>
persona.erc_4337?.includes(acc.value)
)
: []
}
Expand Down
4 changes: 3 additions & 1 deletion apps/passport/app/routes/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ export default function SettingsLayout() {

// need to identify only once
useEffect(() => {
if (!isIdentified) posthog?.identify(identityURN)
if (!isIdentified) {
posthog?.identify(identityURN)
}
setIsIdentified(true)
}, [isIdentified])

Expand Down
22 changes: 0 additions & 22 deletions apps/passport/app/routes/settings/accounts/rename.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
import type { ActionFunction } from '@remix-run/cloudflare'
import { getCoreClient } from '~/platform.server'
import {
getDefaultAuthzParams,
getValidatedSessionContext,
} from '~/session.server'
import { getRollupReqFunctionErrorWrapper } from '@proofzero/utils/errors'
import { createAnalyticsEvent } from '@proofzero/utils/analytics'

export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
async ({ request, context }) => {
const { identityURN } = await getValidatedSessionContext(
request,
getDefaultAuthzParams(request),
context.env,
context.traceSpan
)

const formData = await request.formData()
const name = formData.get('name') as string
const accountURN = formData.get('id') as string
Expand All @@ -25,16 +13,6 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
nickname: name,
})

await createAnalyticsEvent({
apiKey: context.env.POSTHOG_API_KEY,
distinctId: identityURN,
eventName: 'account_renamed',
properties: {
accountId: accountURN,
nickname: name,
},
})

return null
}
)
12 changes: 6 additions & 6 deletions apps/passport/app/routes/settings/advanced.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
await coreClient.identity.deleteIdentityNode.mutate({
identity: identityURN,
})

await createAnalyticsEvent({
apiKey: context.env.POSTHOG_API_KEY,
eventName: 'identity_deleted_identity',
distinctId: identityURN,
})
} catch (ex) {
console.error(ex)
throw new RollupError({
Expand All @@ -89,12 +95,6 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
})
}

await createAnalyticsEvent({
apiKey: context.env.POSTHOG_API_KEY,
eventName: 'delete_rollup_identity',
distinctId: identityURN,
})

return await destroyUserSession(
request,
'/',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import { getCoreClient } from '~/platform.server'
import { getFlashSession, commitFlashSession } from '~/session.server'
import { BadRequestError } from '@proofzero/errors'
import { getRollupReqFunctionErrorWrapper } from '@proofzero/utils/errors'
import { createAnalyticsEvent } from '@proofzero/utils/analytics'

export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
async ({ request, params, context }) => {
const session = await getFlashSession(request, context.env)

const { jwt, identityURN } = await getValidatedSessionContext(
const { jwt } = await getValidatedSessionContext(
request,
context.authzQueryParams,
context.env,
Expand All @@ -33,16 +32,6 @@ export const action: ActionFunction = getRollupReqFunctionErrorWrapper(
issuer: new URL(request.url).origin,
})

await createAnalyticsEvent({
apiKey: context.env.POSTHOG_API_KEY,
distinctId: identityURN,
eventName: 'app_authorization_revoked',
properties: {
clientId,
},
groups: { app: clientId },
})

session.flash(
'tooltipMessage',
JSON.stringify({
Expand Down
5 changes: 1 addition & 4 deletions packages/utils/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,17 @@ export const createAnalyticsEvent = async ({
apiKey,
distinctId,
properties,
groups,
}: {
eventName: string
apiKey: string
distinctId: string
groups?: Record<string, any>
properties?: Record<string, any>
}) => {
const body = JSON.stringify({
api_key: apiKey,
event: eventName,
distinct_id: distinctId,
groups: groups,
properties: properties,
properties,
})

const init = {
Expand Down
8 changes: 5 additions & 3 deletions platform/account/src/jsonrpc/methods/resolveIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export const resolveIdentityMethod = async ({
}): Promise<ResolveIdentityResult> => {
const nodeClient = ctx.account

let eventName = 'identity-resolved'
let eventName = 'account_resolved_identity'

let resultURN = await nodeClient?.class.getIdentity()
if (input.jwt && resultURN) {
Expand All @@ -56,7 +56,7 @@ export const resolveIdentityMethod = async ({
} else {
const name = hexlify(randomBytes(IDENTITY_OPTIONS.length))
urn = IdentityURNSpace.componentizedUrn(name)
eventName = 'identity-created'
eventName = 'account_created_identity'
}
const caller = router.createCaller(ctx)
await caller.account.setIdentity(urn) // this will lazy create an identity node when identity worker is called
Expand All @@ -73,7 +73,9 @@ export const resolveIdentityMethod = async ({
apiKey: ctx.POSTHOG_API_KEY,
eventName,
distinctId: resultURN,
groups: { app: input.clientId },
properties: {
$groups: { app: input.clientId },
},
})

return {
Expand Down
Loading

0 comments on commit 71aca00

Please sign in to comment.