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 | import { eq } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { db, schema } from '@/db' import { withAuth } from '@/lib/auth/withAuth' import { generateFamilyCode, parentChild } from '@/db/schema' import { DEFAULT_SESSION_PREFERENCES, playerSessionPreferences, } from '@/db/schema/player-session-preferences' import type { GameBreakSettings, GeneratedProblem } from '@/db/schema/session-plans' import { approveSessionPlan, generateSessionPlan, initializeStudent, startSessionPlan, } from '@/lib/curriculum' import { setPracticingSkills } from '@/lib/curriculum/progress-manager' import { PRACTICE_APPROVED_GAMES } from '@/lib/arcade/practice-approved-game-list' import { getUserId } from '@/lib/viewer' import { subscriptions } from '@/db/schema/subscriptions' /** * Debug presets for quick session creation */ const PRESETS = { /** 2 parts (abacus + visualization), 1 problem each, auto-start matching game break */ 'game-break': { durationMinutes: 2, enabledParts: { abacus: true, visualization: true, linear: false }, overrideProblemsPerPart: 1, gameBreakSettings: { enabled: true, maxDurationMinutes: 2, selectionMode: 'auto-start' as const, selectedGame: 'matching', skipSetupPhase: true, useAdaptiveSelection: false, } satisfies GameBreakSettings, }, /** 1 part (abacus only), 1 problem, no game break */ minimal: { durationMinutes: 1, enabledParts: { abacus: true, visualization: false, linear: false }, overrideProblemsPerPart: 1, gameBreakSettings: { enabled: false, maxDurationMinutes: 0, selectionMode: 'kid-chooses' as const, selectedGame: null, skipSetupPhase: true, useAdaptiveSelection: false, } satisfies GameBreakSettings, }, } as const type PresetName = keyof typeof PRESETS /** * POST /api/debug/practice-session * * Creates a debug practice session atomically: * 1. Creates a debug player owned by the current viewer * 2. Initializes curriculum and enables basic skills * 3. Generates, approves, and starts a session with the specified preset * 4. Returns the player ID and redirect URL * * When `setupOnly: true`, skips session generation (steps 3-4) and returns * player info so the caller can open the StartPracticeModal instead. */ export const POST = withAuth( async (req: NextRequest) => { try { const body = await req.json() const preset = (body.preset as PresetName) || 'game-break' const setupOnly = body.setupOnly === true const simulateFamilyTier = body.simulateFamilyTier !== false // default true const overrideProblemTerms = body.overrideProblemTerms as number[] | undefined if (!(preset in PRESETS)) { return NextResponse.json( { error: `Unknown preset: ${preset}. Available: ${Object.keys(PRESETS).join(', ')}` }, { status: 400 } ) } const config = PRESETS[preset] // 1. Get current viewer's database user ID const userId = await getUserId() // 2. Create debug player const [player] = await db .insert(schema.players) .values({ userId, name: `Debug-${Date.now()}`, emoji: '🐛', color: '#ff6b6b', isActive: false, isExpungeable: true, familyCode: generateFamilyCode(), }) .returning() // 2b. Create parent-child relationship (required for access control) await db.insert(parentChild).values({ parentUserId: userId, childPlayerId: player.id, }) // 2c. Ensure the user has a family subscription for debug testing if (simulateFamilyTier) { const existing = await db .select() .from(subscriptions) .where(eq(subscriptions.userId, userId)) .limit(1) if (existing.length === 0) { await db.insert(subscriptions).values({ userId, stripeCustomerId: `cus_debug_${Date.now()}`, stripeSubscriptionId: `sub_debug_${Date.now()}`, plan: 'family', status: 'active', currentPeriodEnd: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), }) } else if (existing[0].plan !== 'family' || existing[0].status !== 'active') { await db .update(subscriptions) .set({ plan: 'family', status: 'active' }) .where(eq(subscriptions.userId, userId)) } } // 3. Initialize curriculum await initializeStudent(player.id) // 4. Enable basic skills await setPracticingSkills(player.id, ['basic.+1', 'basic.+2', 'basic.+3']) // If setupOnly, save preset config as player session preferences // so the StartPracticeModal initializes with the preset's settings if (setupOnly) { await db.insert(playerSessionPreferences).values({ playerId: player.id, config: JSON.stringify({ ...DEFAULT_SESSION_PREFERENCES, durationMinutes: config.durationMinutes, partWeights: { abacus: config.enabledParts.abacus ? 1 : 0, visualization: config.enabledParts.visualization ? 1 : 0, linear: config.enabledParts.linear ? 1 : 0, }, gameBreakEnabled: config.gameBreakSettings.enabled, gameBreakMinutes: config.gameBreakSettings.maxDurationMinutes, gameBreakSelectionMode: config.gameBreakSettings.selectionMode, gameBreakSelectedGame: config.gameBreakSettings.selectedGame, gameBreakEnabledGames: [...PRACTICE_APPROVED_GAMES], }), updatedAt: Date.now(), }) return NextResponse.json({ playerId: player.id, playerName: player.name, preset, setupOnly: true, }) } // 5. Generate session with preset config const plan = await generateSessionPlan({ playerId: player.id, durationMinutes: config.durationMinutes, enabledParts: config.enabledParts, overrideProblemsPerPart: config.overrideProblemsPerPart, gameBreakSettings: config.gameBreakSettings, }) // 5b. Override the first problem if custom terms were provided if (overrideProblemTerms && overrideProblemTerms.length > 0) { const customProblem: GeneratedProblem = { terms: overrideProblemTerms, answer: overrideProblemTerms.reduce((a, b) => a + b, 0), skillsRequired: [], } const updatedParts = plan.parts.map((part, i) => i === 0 ? { ...part, slots: part.slots.map((slot, j) => j === 0 ? { ...slot, problem: customProblem } : slot ), } : part ) await db .update(schema.sessionPlans) .set({ parts: updatedParts }) .where(eq(schema.sessionPlans.id, plan.id)) } // 6. Approve and start await approveSessionPlan(plan.id) await startSessionPlan(plan.id) // 7. Return redirect URL return NextResponse.json({ playerId: player.id, sessionId: plan.id, preset, redirectUrl: `/practice/${player.id}?debug=1`, }) } catch (error) { console.error('[debug/practice-session] Failed:', error) return NextResponse.json( { error: error instanceof Error ? error.message : 'Failed to create debug session' }, { status: 500 } ) } }, { role: 'admin' } ) |