Skip to content

Commit

Permalink
Merge pull request #485 from NaucMeIT/feat/add-posthog-analytics-to-l…
Browse files Browse the repository at this point in the history
…egacy

feat(legacy): 📈 identify users in posthog
  • Loading branch information
BleedingDev authored Nov 24, 2024
2 parents a80c74a + cd23e6f commit eb7d30a
Show file tree
Hide file tree
Showing 5 changed files with 800 additions and 1,197 deletions.
29 changes: 24 additions & 5 deletions apps/legacy_nmit/hooks/useTrackedUser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import posthog from "posthog-js"
import splitbee from "@splitbee/web"
import { signIn, signOut, useSession } from "next-auth/react"
import { useRouter } from "next/router"
Expand All @@ -16,6 +17,8 @@ export const useTrackedUser = () => {
const data = await signOut({ redirect: false, callbackUrl: signUrl })
splitbee.track("Sign out")
splitbee.reset()
posthog.capture('Sign out')
posthog.reset()
if (router && shouldRedirect(router.asPath)) {
router.push(data.url)
}
Expand All @@ -25,7 +28,11 @@ export const useTrackedUser = () => {
async function sign(provider: AllowedOauth): Promise<void>
async function sign(provider: AllowedProviders, email?: string): Promise<void> {
try {
splitbee.track(`${provider} sign attempt`)
posthog.capture('sign_attempt', {
email,
provider,
})
splitbee.track(`${provider} sign attempt ${email ? `with email ${email}` : ""}`)
const isEmail = provider === "email"
setSignStatus("signing")
const signInStatus = await signIn(provider, {
Expand All @@ -38,18 +45,30 @@ export const useTrackedUser = () => {
}
setSignStatus(isEmail ? "send" : "oauth")
} catch (e) {
typeof e === "string" && splitbee.track("Sign error", { signError: e, email, provider })
posthog.capture('sign_failure', {
email,
provider,
error: JSON.stringify(e),
})
splitbee.track("Sign error", { signError: JSON.stringify(e), email, provider })
setSignStatus("error")
}
}

useEffect(() => {
if (status === "authenticated" && data?.user.email) {
const { email, name, planId } = data.user
splitbee.track("Sign success")
splitbee.user.set({
userId: data.user.email,
name: data.user.name,
planId: data.user.planId,
userId: email,
name: name,
planId: planId,
})
posthog.identify(email, { name: name })
posthog.capture('sign_success', {
email,
name,
planId,
})
}
// If status changes, we are sure that user data exist, should prevent duplicate calls
Expand Down
1 change: 1 addition & 0 deletions apps/legacy_nmit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"next-runtime": "^2.4.2",
"nodemailer": "^6.9.16",
"posthog-js": "^1.188.0",
"posthog-node": "^4.2.3",
"react": "^18.3.1",
"react-calendly": "^4.3.1",
"react-dom": "^18.3.1",
Expand Down
36 changes: 36 additions & 0 deletions apps/legacy_nmit/pages/api/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@ import createStripe from "stripe"
import bodyParser from "body-parser"
import { log } from "next-axiom"
import { PaymentStatus } from "@prisma/client"
import { PostHog } from 'posthog-node'
import { prisma } from "../../utils/prisma"

const client = new PostHog(
process.env["NEXT_PUBLIC_POSTHOG_KEY"] || "",
{ host: 'https://eu.i.posthog.com' }
)

const stripe = new createStripe(process.env.STRIPE_SECRET_KEY || "", { apiVersion: "2024-11-20.acacia", typescript: true })
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET || ""

Expand Down Expand Up @@ -72,6 +78,18 @@ async function handlePaymentIntentSucceeded(id: string, email: string) {
where: { email },
data: { credits: user.credits + plan.credits, paymentStatus: PaymentStatus.Done },
})

client.identify({ distinctId: user.id })
client.capture({
distinctId: user.id,
event: 'order_paid',
properties: {
subtotal: plan.price,
customer_email: user.email,
},
})

await client.shutdown()
}

async function handlePaymentIntentInProgress(email: string) {
Expand All @@ -82,6 +100,15 @@ async function handlePaymentIntentInProgress(email: string) {
where: { email },
data: { paymentStatus: PaymentStatus.InProgress },
})

client.identify({ distinctId: user.id })
client.capture({
distinctId: user.id,
event: 'order_in_progress',
properties: {
customer_email: user.email,
},
})
}

async function handlePaymentIntentFailed(email: string) {
Expand All @@ -92,4 +119,13 @@ async function handlePaymentIntentFailed(email: string) {
where: { email },
data: { paymentStatus: PaymentStatus.Failed },
})

client.identify({ distinctId: user.id })
client.capture({
distinctId: user.id,
event: 'order_failed',
properties: {
customer_email: user.email,
},
})
}
19 changes: 19 additions & 0 deletions apps/legacy_nmit/pages/profile/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import { ProfileDetailsForm } from "../../components/ProfileDetailsForm"
import { prisma } from "../../utils/prisma"
import { PaymentStatus, Plan } from "@prisma/client"
import { allowedStatus } from "../../utils/stripe"
import { PostHog } from 'posthog-node'

const client = new PostHog(
process.env["NEXT_PUBLIC_POSTHOG_KEY"] || "",
{ host: 'https://eu.i.posthog.com' }
)

type PageProps = {
readonly session: Session
Expand Down Expand Up @@ -98,6 +104,19 @@ export const getServerSideProps = handle<{}, UrlQuery, FormData>({
paymentStatus: isPaidPlan ? PaymentStatus.Awaiting : PaymentStatus.NotNecessary,
},
})
const userEmail = session?.user?.email || ""
client.identify({ distinctId: userEmail, properties: {
name: body.name,
} })
client.capture({
distinctId: userEmail,
event: 'profile_edited',
properties: {
subtotal: dbPlan.price,
customer_email: userEmail,
},
})
await client.shutdown()

return {
redirect: {
Expand Down
Loading

1 comment on commit eb7d30a

@vercel
Copy link

@vercel vercel bot commented on eb7d30a Nov 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

web – ./apps/legacy_nmit

web-git-master-naucmeits-projects.vercel.app
naucme.it
web-naucmeits-projects.vercel.app

Please sign in to comment.