All files / routes stats.ts

100% Statements 47/47
100% Branches 42/42
100% Functions 7/7
100% Lines 47/47

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                                                1x     1x 1x           16x             8x 8x 8x                     1x 5x 5x 5x 5x 5x   5x 5x 1x       4x 4x       4x                 3x 5x 5x     5x                           1x                   1x                     5x       5x   1x                       1x 8x 8x 8x 8x   8x 1x       7x 7x 2x       5x         5x 1x             4x 4x   4x           3x 1x                         1x          
// Stats API Routes - Pro and Project Analytics
import { Hono } from "hono";
import type { Dal } from "../dal";
import { type DualCache, CACHE_TTL, MARKETPLACE } from "../lib/cache";
import { success, handleError } from "../lib/response";
import {
	requireAuth,
	requireProAccess,
	contextMiddleware,
} from "../middleware";
import { ValidationError, ForbiddenError, NotFoundError } from "../lib/errors";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		cache: DualCache;
		proId: string;
		proRole: string;
	};
};
 
const stats = new Hono<Env>();
 
// Apply middleware to all stats routes
stats.use("*", contextMiddleware);
stats.use("*", requireAuth);
 
/**
 * Helper function to format date as YYYY-MM-DD
 */
function formatDate(date: Date): string {
	return date.toISOString().split("T")[0];
}
 
/**
 * Helper function to get date N days ago
 */
function getDaysAgo(days: number): string {
	const date = new Date();
	date.setDate(date.getDate() - days);
	return formatDate(date);
}
 
// ============================================================================
// Pro Stats
// ============================================================================
 
/**
 * GET /api/stats/pro/:proId
 * Get analytics for a pro (requires pro ownership)
 */
stats.get("/pro/:proId", requireProAccess, async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
		const cache = c.get("cache");
		const cacheKey = MARKETPLACE.proStats(proId);
 
		const cached = await cache.get<unknown>(cacheKey);
		if (cached) {
			return c.json({ success: true, data: cached });
		}
 
		// Calculate date range for daily data
		const endDate = formatDate(new Date());
		const startDate = getDaysAgo(30);
 
		// Fetch all data in parallel for better performance
		const [summary, daily, topProjects, latestDaily, totalLeads] =
			await Promise.all([
				dal.analytics.getProSummary(proId),
				dal.analytics.getProDaily(proId, startDate, endDate),
				dal.analytics.getTopProjects(proId, 5),
				dal.analytics.getProLatestDaily(proId),
				dal.leads.countByProId(proId),
			]);
 
		// Parse JSON fields from latest daily record
		const sources = latestDaily?.sources || {};
		const devices = latestDaily?.devices || {};
		const cities = latestDaily?.cities || {};
 
		// Format response
		const responseData = {
			summary: {
				totalPageViews: summary?.totalPageViews || 0,
				totalProjectClicks: summary?.totalProjectClicks || 0,
				totalWhatsappClicks: summary?.totalWhatsappClicks || 0,
				totalCallClicks: summary?.totalCallClicks || 0,
				totalInquiries: totalLeads,
				views7d: summary?.views7d || 0,
				views30d: summary?.views30d || 0,
				clicks7d: summary?.clicks7d || 0,
				clicks30d: summary?.clicks30d || 0,
				lastViewAt: summary?.lastViewAt || null,
				lastClickAt: summary?.lastClickAt || null,
			},
			daily: daily.map((d: { date: string; pageViews: number; projectClicks: number; imageClicks: number; whatsappClicks: number; callClicks: number; inquiryClicks: number; uniqueSessions: number }) => ({
				date: d.date,
				pageViews: d.pageViews,
				projectClicks: d.projectClicks,
				imageClicks: d.imageClicks,
				whatsappClicks: d.whatsappClicks,
				callClicks: d.callClicks,
				inquiryClicks: d.inquiryClicks,
				uniqueSessions: d.uniqueSessions,
			})),
			topProjects: topProjects.map((p: { id: string; title: string; slug: string | null; viewCount: number }) => ({
				id: p.id,
				title: p.title,
				slug: p.slug,
				views: p.viewCount,
			})),
			sources,
			devices,
			cities,
		};
 
		c.executionCtx.waitUntil(
			cache.put(cacheKey, responseData, { l1Ttl: CACHE_TTL.PRO_STATS_L1, l2Ttl: CACHE_TTL.PRO_STATS_L2 }),
		);
 
		return success(c, responseData);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// Project Stats
// ============================================================================
 
/**
 * GET /api/stats/project/:projectId
 * Get analytics for a project (requires project ownership via pro)
 */
stats.get("/project/:projectId", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const projectId = c.req.param("projectId");
 
		if (!user) {
			return handleError(c, new ValidationError("Authentication required"));
		}
 
		// Get the project to verify ownership (need proId for auth check)
		const project = await dal.projects.findById(projectId);
		if (!project) {
			return handleError(c, new NotFoundError("Project not found"));
		}
 
		// Check user role and platform admin status in parallel
		const [userRole, isPlatformAdmin] = await Promise.all([
			dal.userTenantRoles.findUserProRole(user.id, project.proId),
			dal.userTenantRoles.isPlatformAdmin(user.id),
		]);
 
		if (!userRole && !isPlatformAdmin) {
			return handleError(
				c,
				new ForbiddenError("You do not have access to this project"),
			);
		}
 
		// Calculate date range and fetch analytics data in parallel
		const endDate = formatDate(new Date());
		const startDate = getDaysAgo(30);
 
		const [daily, totals] = await Promise.all([
			dal.analytics.getProjectDaily(projectId, startDate, endDate),
			dal.analytics.getProjectTotals(projectId),
		]);
 
		// Format response
		return success(c, {
			daily: daily.map((d) => ({
				date: d.date,
				pageViews: d.pageViews,
				imageClicks: d.imageClicks,
				uniqueSessions: d.uniqueSessions,
			})),
			totals: {
				totalPageViews: totals?.totalPageViews || 0,
				totalImageClicks: totals?.totalImageClicks || 0,
				totalUniqueSessions: totals?.totalUniqueSessions || 0,
			},
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default stats;