Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(tt): survey page for year end survey #1763

Merged
merged 14 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
"typescript.tsdk": "node_modules/typescript/lib",
"cSpell.words": [
"trpc"
]
}
3 changes: 3 additions & 0 deletions apps/epic-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@
},
"dependencies": {
"@amplitude/analytics-browser": "^1.3.0",
"@amplitude/analytics-node": "^1.3.4",
"@amplitude/identify": "^1.10.2",
"@amplitude/node": "^1.10.2",
"@aws-sdk/client-s3": "^3.441.0",
"@aws-sdk/s3-request-presigner": "^3.441.0",
"@cloudinary/react": "^1.5.0",
Expand Down
81 changes: 81 additions & 0 deletions apps/epic-web/src/inngest/functions/sync-conversions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import {prisma} from '@skillrecordings/database'

import * as Amplitude from '@amplitude/node'
import {Identify} from '@amplitude/identify'
import {inngest} from 'inngest/inngest.server'

export const syncConversions = inngest.createFunction(
{
id: 'sync-conversions',
name: 'Sync Conversions',
},
{
event: 'analytics/conversion',
},
async ({event, step}) => {
const BATCH_SIZE = 100
const amplitude = Amplitude.init(process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY!)
const listOfPurchases = await step.run(
`get list of purchases`,
async () => {
return prisma.purchase.findMany({
where: {
status: {
in: ['Valid', 'Restricted'],
},
productId: {
in: [
'0143b3f6-d5dd-4f20-9898-38da609799ca',
'1b6e7ed6-8a15-48f1-8dd7-e76612581ee8',
'2267e543-51fa-4d71-a02f-ad9ba71a1f8e',
'2e5b2993-d069-4e43-a7f1-24cffa83f7ac',
'5809fd2e-8072-42eb-afa2-aff7c9999d0c',
'5ffdd0ef-a7a3-431e-b36b-f4232da7e454',
'7872d512-ba34-4108-b510-7db9cbcee98c',
'dc9b750c-e3bc-4b0a-b7d2-d04a481afa0d',
'f3f85931-e67e-456f-85c4-eec95a0e4ddd',
'kcd_product_dbf94bf0-66b0-11ee-8c99-0242ac120002',
],
},
},
include: {
user: true,
},
take: BATCH_SIZE,
skip: event.data.offset || 0,
})
},
)

for (const purchase of listOfPurchases) {
if (!purchase.user) continue

await step.run('send to amplitude', async () => {
if (!purchase.user) return
const identify = new Identify()
await amplitude.identify(purchase.user.email, null, identify)
await amplitude.logEvent({
event_type: 'purchase',
user_id: purchase.user.email,
time: new Date(purchase.createdAt).getTime(),
...(purchase.country && {country: purchase.country}),
event_properties: {
product: purchase.productId,
total: purchase.totalAmount,
status: purchase.status,
},
})
})
}

if (listOfPurchases.length === BATCH_SIZE) {
await step.sendEvent('send next batch', {
name: 'analytics/conversion',
data: {
offset: (event.data.offset || 0) + BATCH_SIZE,
},
})
}
return event.data.offset || 0
},
)
2 changes: 2 additions & 0 deletions apps/epic-web/src/inngest/inngest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {discordAccountLinked} from 'inngest/functions/discord/discord-account-li
import {syncDiscordRoles} from 'inngest/functions/discord/sync-discord-roles'
import {slackDailyReporter} from './functions/stripe/slack-daily-reporter'
import {slackMonthlyReporter} from './functions/stripe/slack-monthly-reporter'
import {syncConversions} from 'inngest/functions/sync-conversions'

export const inngestConfig = {
client: inngest,
Expand All @@ -30,6 +31,7 @@ export const inngestConfig = {
syncDiscordRoles,
slackDailyReporter,
slackMonthlyReporter,
syncConversions,
...sanityProductFunctions,
],
}
1 change: 1 addition & 0 deletions apps/epic-web/src/inngest/inngest.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export type IngestEvents = {
[PURCHASE_STATUS_UPDATED_EVENT]: PurchaseStatusUpdated
'user/login': {}
'user/created': {}
'analytics/conversion': {}
}
export const inngest = new Inngest({
id: process.env.INNGEST_APP_NAME || process.env.NEXT_PUBLIC_SITE_TITLE,
Expand Down
35 changes: 35 additions & 0 deletions apps/epic-web/src/pages/api/skill/[...skillRecordings].ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import {
defaultPaymentOptions,
StripeProvider,
} from '@skillrecordings/commerce-server'
import {getSdk} from '@skillrecordings/database'
import * as Amplitude from '@amplitude/node'
import {Identify} from '@amplitude/identify'

export const paymentOptions = defaultPaymentOptions({
stripeProvider: StripeProvider({
Expand All @@ -29,6 +32,38 @@ export const skillOptions: SkillRecordingsOptions = {
const token = await getToken({req: req as unknown as NextApiRequest})
return getCurrentAbility({user: UserSchema.parse(token)})
},
onPurchase: async (purchaseId: string) => {
const {getPurchase, getUserById} = getSdk()
const purchase = await getPurchase({
where: {id: purchaseId},
})

if (!purchase || !purchase.userId) return

const user = await getUserById({
where: {id: purchase.userId},
})

if (!user) return

if (purchase?.status === 'Valid' || purchase?.status === 'Restricted') {
const amplitude = Amplitude.init(
process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY!,
)
const identify = new Identify()
await amplitude.identify(user.email, null, identify)
await amplitude.logEvent({
event_type: 'purchase',
user_id: user.email,
event_properties: {
product: purchase.productId,
country: purchase.country,
total: purchase.totalAmount,
status: purchase.status,
},
})
}
},
}

export default SkillRecordings(skillOptions)
Expand Down
52 changes: 41 additions & 11 deletions apps/total-typescript/src/offer/offer-machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@ export type OfferMachineEvent =
| {type: 'DISMISSAL_ACKNOWLEDGED'}
| {type: 'OFFER_COMPLETE'}
| {type: 'SUBSCRIBED'}

| {type: 'EMAIL_COLLECTED'}
export type OfferContext = {
subscriber?: Subscriber
currentOffer: Offer
currentOfferId: string
eligibility?: StateMachine<any, any, any> | null
canSurveyAnon?: boolean
askAllQuestions?: boolean
bypassNagProtection?: boolean
}

export const offerMachine = createMachine<OfferContext, OfferMachineEvent>(
Expand All @@ -41,7 +44,7 @@ export const offerMachine = createMachine<OfferContext, OfferMachineEvent>(
}),
},
NO_SUBSCRIBER_FOUND: {
target: 'offerComplete',
target: 'verifyingOfferEligibility',
},
},
},
Expand All @@ -66,23 +69,37 @@ export const offerMachine = createMachine<OfferContext, OfferMachineEvent>(
target: 'presentingCurrentOffer',
actions: assign({
currentOffer: (_, event) => {
console.log('set currentOffer', event.currentOffer)
return event.currentOffer
},
currentOfferId: (_, event) => {
console.log('set currentOfferId', event.currentOfferId)
return event.currentOfferId
},
}),
},
NO_CURRENT_OFFER_FOUND: {
target: 'offerComplete',
},
NO_CURRENT_OFFER_FOUND: [
{
target: 'offerComplete',
cond: (context) => Boolean(context.subscriber),
},
{
target: 'collectEmail',
},
],
},
},
presentingCurrentOffer: {
on: {
RESPONDED_TO_OFFER: {
target: 'offerComplete',
},
RESPONDED_TO_OFFER: [
{
target: 'loadingCurrentOffer',
cond: (context) => context.askAllQuestions === true,
},
{
target: 'offerComplete',
},
],
OFFER_DISMISSED: {
target: 'offerComplete',
},
Expand All @@ -91,6 +108,13 @@ export const offerMachine = createMachine<OfferContext, OfferMachineEvent>(
},
},
},
collectEmail: {
on: {
EMAIL_COLLECTED: {
target: 'offerComplete',
},
},
},
offerComplete: {
type: 'final',
},
Expand All @@ -101,6 +125,11 @@ export const offerMachine = createMachine<OfferContext, OfferMachineEvent>(
verifyEligibility: (context, _) =>
new Promise((resolve, reject) => {
const {subscriber} = context

if (!subscriber && context.canSurveyAnon) {
resolve(true)
}

const lastSurveyDate = new Date(
subscriber?.fields.last_surveyed_on || 0,
)
Expand All @@ -109,10 +138,11 @@ export const offerMachine = createMachine<OfferContext, OfferMachineEvent>(
new Date(),
DAYS_TO_WAIT_BETWEEN_QUESTIONS,
)

const canSurvey =
isBefore(lastSurveyDate, thresholdDate) &&
subscriber?.fields.do_not_survey !== 'true' &&
subscriber?.state === 'active'
context.bypassNagProtection ||
(isBefore(lastSurveyDate, thresholdDate) &&
subscriber?.fields.do_not_survey !== 'true')

if (canSurvey) {
resolve(true)
Expand Down
Loading
Loading