// src/lib/analytics/reports.ts
import { PostHog } from 'posthog-node'
import { env } from '@/env.mjs'
const client = new PostHog(env.POSTHOG_API_KEY)
interface DateRange {
startDate: Date
endDate: Date
}
export async function generateUserReport(
dateRange: DateRange
) {
const { startDate, endDate } = dateRange
const [signups, activeUsers, retention] = await Promise.all([
client.events.list({
event: 'sign_up',
from: startDate.toISOString(),
to: endDate.toISOString(),
}),
client.trends.active_users({
from: startDate.toISOString(),
to: endDate.toISOString(),
}),
client.retention.list({
from: startDate.toISOString(),
to: endDate.toISOString(),
}),
])
return {
signups: signups.length,
activeUsers,
retention,
}
}
export async function generateFeatureReport(
featureId: string,
dateRange: DateRange
) {
const { startDate, endDate } = dateRange
const events = await client.events.list({
event: 'feature_used',
properties: {
featureId,
},
from: startDate.toISOString(),
to: endDate.toISOString(),
})
const usageByDay = events.reduce((acc, event) => {
const date = new Date(event.timestamp).toISOString().split('T')[0]
acc[date] = (acc[date] || 0) + 1
return acc
}, {} as Record<string, number>)
return {
totalUsage: events.length,
usageByDay,
}
}