All files / app/(dashboard)/analytics page.tsx

98.14% Statements 212/216
91.89% Branches 68/74
100% Functions 3/3
98.14% Lines 212/216

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 3031x               1x 1x 1x 1x                                                       32x 32x 1x 1x   12x 12x 12x 12x 12x 12x 12x     12x 12x 12x 12x 12x 12x   12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x     8x 8x 8x     8x 12x 248x 248x 248x 248x   8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x   8x 14x 14x   14x     14x 14x   14x 10x 10x   10x 9x 9x 14x 4x 4x   4x 1x 1x 4x 1x 3x 2x 2x     4x 2x 2x 2x 2x 2x 2x 4x   14x     14x 4x 4x 4x 4x 4x 1x 1x 14x 10x 10x     14x 13x 13x 13x 3x 13x 1x 1x 13x 13x 8x     8x 8x 8x 8x 1x         8x 12x 12x     12x 12x 12x 8x 1x 12x     12x 12x 192x 192x     8x 8x 8x   8x 12x 1x 1x   1x 1x 1x 1x 1x 1x 1x     8x 8x 8x   8x 8x 8x   8x 8x 8x 8x   8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   14x 14x 14x 1x 1x   13x 13x 13x 13x 13x 13x   14x 1x 1x   14x 14x     14x   12x 12x 12x 12x 12x 12x   12x 8x 8x 8x 8x 8x 8x     14x 14x   14x  
import { Metadata } from 'next';
import { redirect } from 'next/navigation';
import { getUser, createClient } from '@/lib/supabase/server';
import { getAdminClient } from '@/lib/supabase/admin';
import { AnalyticsDashboard } from '@/components/analytics/AnalyticsDashboard';
import { UpgradePrompt } from '@/components/subscription/UpgradePrompt';
import { getAnalyticsLevel, type SubscriptionTier } from '@/lib/subscription/tiers';
 
export const metadata: Metadata = {
  title: 'Analytics - ProofID',
  description: 'View detailed analytics for your ProofID profile',
};
 
export interface AnalyticsData {
  dailyViews: { date: string; views: number; clicks: number }[];
  eventBreakdown: { type: string; count: number }[];
  topReferrers: { source: string; count: number }[];
  deviceBreakdown: { device: string; count: number }[];
  totals: {
    views: number;
    clicks: number;
    whatsappClicks: number;
    ctr: number;
  };
  // Pro tier (advanced)
  growth: {
    views: number;
    clicks: number;
    whatsappClicks: number;
    ctr: number;
  };
  uniqueVisitors: number;
  peakHours: { hour: number; count: number }[];
  visitorRetention: { new: number; returning: number };
  // Premium tier (full)
  conversionFunnel: { views: number; contentClicks: number; contacts: number };
  topContent: { sampleId: string; title: string; clicks: number }[];
}
 
function computeGrowthPct(current: number, previous: number): number {
  if (previous === 0) return current > 0 ? 100 : 0;
  return ((current - previous) / previous) * 100;
}
 
async function getAnalyticsData(profileId: string, days: number = 30): Promise<AnalyticsData> {
  const adminClient = getAdminClient();
  const now = new Date();
  const startDate = new Date(now);
  startDate.setDate(startDate.getDate() - days);
  const prevStart = new Date(now);
  prevStart.setDate(prevStart.getDate() - days * 2);
 
  // Fetch current + previous period in one query (last 60 days)
  const { data: allEvents } = await adminClient
    .from('analytics')
    .select('event_type, created_at, meta, referrer, user_agent, ip_hash')
    .eq('profile_id', profileId)
    .gte('created_at', prevStart.toISOString())
    .order('created_at', { ascending: true });
 
  const emptyResult: AnalyticsData = {
    dailyViews: [],
    eventBreakdown: [],
    topReferrers: [],
    deviceBreakdown: [],
    totals: { views: 0, clicks: 0, whatsappClicks: 0, ctr: 0 },
    growth: { views: 0, clicks: 0, whatsappClicks: 0, ctr: 0 },
    uniqueVisitors: 0,
    peakHours: [],
    visitorRetention: { new: 0, returning: 0 },
    conversionFunnel: { views: 0, contentClicks: 0, contacts: 0 },
    topContent: [],
  };
 
  if (!allEvents || allEvents.length === 0) return emptyResult;
 
  // Split into current and previous period
  const startTs = startDate.getTime();
  const currentEvents = allEvents.filter((e) => new Date(e.created_at).getTime() >= startTs);
  const previousEvents = allEvents.filter((e) => new Date(e.created_at).getTime() < startTs);
 
  // Process daily views
  const dailyMap = new Map<string, { views: number; clicks: number }>();
  for (let i = 0; i <= days; i++) {
    const date = new Date(now);
    date.setDate(date.getDate() - i);
    dailyMap.set(date.toISOString().split('T')[0], { views: 0, clicks: 0 });
  }
 
  const eventCounts = new Map<string, number>();
  const referrerCounts = new Map<string, number>();
  const deviceCounts = new Map<string, number>();
  const hourCounts = new Map<number, number>();
  const viewerIpCounts = new Map<string, number>();
  const sampleClickCounts = new Map<string, number>();
 
  let totalViews = 0;
  let totalClicks = 0;
  let whatsappClicks = 0;
  let contentClicks = 0;
  let contacts = 0;
 
  currentEvents.forEach((event) => {
    const dateStr = new Date(event.created_at).toISOString().split('T')[0];
    const daily = dailyMap.get(dateStr) || { views: 0, clicks: 0 };
 
    eventCounts.set(event.event_type, (eventCounts.get(event.event_type) || 0) + 1);
 
    // Peak hours
    const hour = new Date(event.created_at).getHours();
    hourCounts.set(hour, (hourCounts.get(hour) || 0) + 1);
 
    if (event.event_type === 'profile_view') {
      daily.views++;
      totalViews++;
      // Track unique visitors by ip_hash
      if (event.ip_hash) {
        viewerIpCounts.set(event.ip_hash, (viewerIpCounts.get(event.ip_hash) || 0) + 1);
      }
    } else {
      daily.clicks++;
      totalClicks++;
 
      if (event.event_type === 'whatsapp_click') {
        whatsappClicks++;
        contacts++;
      } else if (event.event_type === 'email_click') {
        contacts++;
      } else if (event.event_type === 'sample_click' || event.event_type === 'package_view') {
        contentClicks++;
      }
 
      // Track sample clicks for top content
      if (event.event_type === 'sample_click') {
        const meta = event.meta as Record<string, unknown> | null;
        const sampleId = meta?.sample_id as string | undefined;
        if (sampleId) {
          sampleClickCounts.set(sampleId, (sampleClickCounts.get(sampleId) || 0) + 1);
        }
      }
    }
 
    dailyMap.set(dateStr, daily);
 
    // Referrer
    if (event.referrer) {
      try {
        const url = new URL(event.referrer);
        const source = url.hostname.replace('www.', '');
        referrerCounts.set(source, (referrerCounts.get(source) || 0) + 1);
      } catch {
        referrerCounts.set('Direct', (referrerCounts.get('Direct') || 0) + 1);
      }
    } else {
      referrerCounts.set('Direct', (referrerCounts.get('Direct') || 0) + 1);
    }
 
    // Device
    if (event.user_agent) {
      const ua = event.user_agent.toLowerCase();
      let device = 'Desktop';
      if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone')) {
        device = 'Mobile';
      } else if (ua.includes('tablet') || ua.includes('ipad')) {
        device = 'Tablet';
      }
      deviceCounts.set(device, (deviceCounts.get(device) || 0) + 1);
    }
  });
 
  // Previous period totals for growth calculation
  let prevViews = 0;
  let prevClicks = 0;
  let prevWhatsapp = 0;
  previousEvents.forEach((e) => {
    if (e.event_type === 'profile_view') prevViews++;
    else {
      prevClicks++;
      if (e.event_type === 'whatsapp_click') prevWhatsapp++;
    }
  });
  const prevCtr = prevViews > 0 ? (prevClicks / prevViews) * 100 : 0;
  const currentCtr = totalViews > 0 ? (totalClicks / totalViews) * 100 : 0;
 
  // Visitor retention
  let newVisitors = 0;
  let returningVisitors = 0;
  viewerIpCounts.forEach((count) => {
    if (count === 1) newVisitors++;
    else returningVisitors++;
  });
 
  // Peak hours (fill all 24 hours)
  const peakHours: { hour: number; count: number }[] = [];
  for (let h = 0; h < 24; h++) {
    peakHours.push({ hour: h, count: hourCounts.get(h) || 0 });
  }
 
  // Top content: get sample titles
  const topSampleIds = Array.from(sampleClickCounts.entries())
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5);
 
  let topContent: { sampleId: string; title: string; clicks: number }[] = [];
  if (topSampleIds.length > 0) {
    const ids = topSampleIds.map(([id]) => id);
    const { data: samples } = await adminClient.from('samples').select('id, title').in('id', ids);
 
    const titleMap = new Map((samples || []).map((s) => [s.id, s.title]));
    topContent = topSampleIds.map(([id, clicks]) => ({
      sampleId: id,
      title: titleMap.get(id) || 'Untitled',
      clicks,
    }));
  }
 
  // Convert maps to sorted arrays
  const dailyViews = Array.from(dailyMap.entries())
    .map(([date, data]) => ({ date, ...data }))
    .sort((a, b) => a.date.localeCompare(b.date));
 
  const eventBreakdown = Array.from(eventCounts.entries())
    .map(([type, count]) => ({ type, count }))
    .sort((a, b) => b.count - a.count);
 
  const topReferrers = Array.from(referrerCounts.entries())
    .map(([source, count]) => ({ source, count }))
    .sort((a, b) => b.count - a.count)
    .slice(0, 10);
 
  const deviceBreakdown = Array.from(deviceCounts.entries())
    .map(([device, count]) => ({ device, count }))
    .sort((a, b) => b.count - a.count);
 
  return {
    dailyViews,
    eventBreakdown,
    topReferrers,
    deviceBreakdown,
    totals: {
      views: totalViews,
      clicks: totalClicks,
      whatsappClicks,
      ctr: currentCtr,
    },
    growth: {
      views: computeGrowthPct(totalViews, prevViews),
      clicks: computeGrowthPct(totalClicks, prevClicks),
      whatsappClicks: computeGrowthPct(whatsappClicks, prevWhatsapp),
      ctr: computeGrowthPct(currentCtr, prevCtr),
    },
    uniqueVisitors: viewerIpCounts.size,
    peakHours,
    visitorRetention: { new: newVisitors, returning: returningVisitors },
    conversionFunnel: { views: totalViews, contentClicks, contacts },
    topContent,
  };
}
 
export default async function AnalyticsPage() {
  const user = await getUser();
  if (!user) {
    redirect('/login');
  }
 
  const supabase = await createClient();
  const { data: profile } = await supabase
    .from('profiles')
    .select('id, subscription_tier')
    .eq('user_id', user.id)
    .single();
 
  if (!profile) {
    redirect('/onboarding');
  }
 
  const tier = (profile.subscription_tier || 'free') as SubscriptionTier;
  const analyticsLevel = getAnalyticsLevel(tier);
 
  // Get analytics data
  const analyticsData = await getAnalyticsData(profile.id, 30);
 
  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-3xl font-bold">Analytics</h1>
        <p className="text-muted-foreground">Track your profile performance and engagement</p>
      </div>
 
      {analyticsLevel === 'basic' && (
        <UpgradePrompt
          currentTier={tier}
          feature="unlock advanced analytics with detailed charts and insights"
          suggestedTier="pro"
          compact
        />
      )}
 
      <AnalyticsDashboard data={analyticsData} analyticsLevel={analyticsLevel} tier={tier} />
    </div>
  );
}