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 | /** * A/B Test API Route * * Handles A/B test variant assignment and conversion tracking. * GET - Get variant assignment for a visitor * POST - Track conversion */ import { NextRequest, NextResponse } from 'next/server'; import { z } from "zod"; import { prisma } from "@/lib/prisma"; import { logger } from "@/lib/logging"; import { withErrorHandling, successResponse, ApiError, ApiSuccessResponse, ApiErrorResponse } from "@/lib/api"; import { Prisma } from "@prisma/client"; // Schema for conversion tracking const conversionSchema = z.object({ experiment: z.string().min(1), visitorId: z.string().min(1).max(50), variant: z.string().min(1), value: z.number().optional()}); interface VariantResponse { variant: string | null; config?: Prisma.JsonValue; } /** * GET - Get variant assignment for a visitor */ async function handleGet( request: NextRequest ): Promise<NextResponse<ApiSuccessResponse<VariantResponse> | ApiErrorResponse>> { const { searchParams } = new URL(request.url); const experimentName = searchParams.get("experiment"); const visitorId = searchParams.get("visitorId"); if (!experimentName || !visitorId) { throw ApiError.badRequest("Missing experiment or visitorId parameter"); } // Check for existing assignment const existingAssignment = await prisma.aBTestAssignment.findFirst({ where: { experiment: { name: experimentName }, visitorId}, include: { variant: true }}); if (existingAssignment) { return successResponse({ variant: existingAssignment.variant.name, config: existingAssignment.variant.config}); } // Get experiment const experiment = await prisma.aBTestExperiment.findUnique({ where: { name: experimentName, status: "RUNNING" }, include: { variants: true }}); if (!experiment) { // Experiment not found or not running return successResponse({ variant: null }); } // Check traffic percentage if (experiment.trafficPercent < 100) { const random = Math.random() * 100; if (random > experiment.trafficPercent) { // Visitor not included in experiment return successResponse({ variant: null }); } } // Assign variant based on weights const totalWeight = experiment.variants.reduce((sum, v) => sum + v.weight, 0); let random = Math.random() * totalWeight; let selectedVariant = experiment.variants[0]; for (const variant of experiment.variants) { random -= variant.weight; if (random <= 0) { selectedVariant = variant; break; } } // Create assignment await prisma.aBTestAssignment.create({ data: { experimentId: experiment.id, variantId: selectedVariant.id, visitorId}}); // Increment impressions await prisma.aBTestVariant.update({ where: { id: selectedVariant.id }, data: { impressions: { increment: 1 } }}); logger.info(`A/B test assignment: ${experimentName} -> ${selectedVariant.name}`, { category: "API", experimentId: experiment.id, variantId: selectedVariant.id, visitorId}); return successResponse({ variant: selectedVariant.name, config: selectedVariant.config}); } export const GET = withErrorHandling(handleGet); /** * POST - Track conversion for A/B test */ async function handlePost( request: NextRequest ): Promise<NextResponse<ApiSuccessResponse<{ alreadyConverted?: boolean }> | ApiErrorResponse>> { const body = await request.json(); const data = conversionSchema.parse(body); // Find the assignment const assignment = await prisma.aBTestAssignment.findFirst({ where: { experiment: { name: data.experiment }, visitorId: data.visitorId, variant: { name: data.variant }}, include: { variant: true }}); if (!assignment) { throw ApiError.notFound("Assignment"); } // Don't update if already converted if (assignment.converted) { return successResponse({ alreadyConverted: true }); } // Update assignment as converted await prisma.aBTestAssignment.update({ where: { id: assignment.id }, data: { converted: true, convertedAt: new Date(), conversionValue: data.value}}); // Increment variant conversions await prisma.aBTestVariant.update({ where: { id: assignment.variantId }, data: { conversions: { increment: 1 } }}); logger.info(`A/B test conversion: ${data.experiment} -> ${data.variant}`, { category: "API", visitorId: data.visitorId, value: data.value}); return successResponse({}); } export const POST = withErrorHandling(handlePost); |