All files / web/src/app/api/create/worksheets route.ts

0% Statements 0/219
0% Branches 0/1
0% Functions 0/1
0% Lines 0/219

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                                                                                                                                                                                                                                                                                                                                                                                                                                                       
// API route for generating addition worksheets

import { NextResponse } from 'next/server'
import { execSync } from 'child_process'
import { eq } from 'drizzle-orm'
import { validateWorksheetConfig } from '@/app/create/worksheets/validation'
import { metrics } from '@/lib/metrics'
import {
  generateProblems,
  generateSubtractionProblems,
  generateMixedProblems,
} from '@/app/create/worksheets/problemGenerator'
import { generateTypstSource } from '@/app/create/worksheets/typstGenerator'
import {
  serializeAdditionConfig,
  type AdditionConfigV4,
} from '@/app/create/worksheets/config-schemas'
import type { WorksheetFormState, WorksheetProblem } from '@/app/create/worksheets/types'
import { db } from '@/db'
import { worksheetShares } from '@/db/schema'
import { generateShareId } from '@/lib/generateShareId'
import { getCurrentTraceId, recordError } from '@/lib/tracing'
import { withAuth } from '@/lib/auth/withAuth'

export const POST = withAuth(async (request) => {
  const startTime = Date.now()
  try {
    const body: WorksheetFormState = await request.json()

    // Validate configuration
    const validation = validateWorksheetConfig(body)
    if (!validation.isValid || !validation.config) {
      return NextResponse.json(
        { error: 'Invalid configuration', errors: validation.errors },
        { status: 400 }
      )
    }

    const config = validation.config

    // Generate problems based on operator type
    let problems: WorksheetProblem[]
    if (config.operator === 'addition') {
      problems = generateProblems(
        config.total,
        config.pAnyStart,
        config.pAllStart,
        config.interpolate,
        config.seed,
        config.digitRange
      )
    } else if (config.operator === 'subtraction') {
      problems = generateSubtractionProblems(
        config.total,
        config.digitRange,
        config.pAnyStart,
        config.pAllStart,
        config.interpolate,
        config.seed
      )
    } else {
      // mixed
      problems = generateMixedProblems(
        config.total,
        config.digitRange,
        config.pAnyStart,
        config.pAllStart,
        config.interpolate,
        config.seed
      )
    }

    // If QR code is enabled, create a share record first
    let shareUrl: string | undefined
    if (config.includeQRCode) {
      try {
        // Generate unique share ID
        let shareId = generateShareId()
        let attempts = 0
        const MAX_ATTEMPTS = 5
        let isUnique = false

        while (!isUnique && attempts < MAX_ATTEMPTS) {
          shareId = generateShareId()
          const existing = await db.query.worksheetShares.findFirst({
            where: eq(worksheetShares.id, shareId),
          })

          if (!existing) {
            isUnique = true
          } else {
            attempts++
          }
        }

        if (!isUnique) {
          console.error('Failed to generate unique share ID for QR code')
          // Continue without QR code rather than failing the entire request
        } else {
          // Get creator IP (hashed for privacy)
          const forwardedFor = request.headers.get('x-forwarded-for')
          const ip = forwardedFor?.split(',')[0] || request.headers.get('x-real-ip') || 'unknown'

          const hashIp = (str: string) => {
            let hash = 0
            for (let i = 0; i < str.length; i++) {
              const char = str.charCodeAt(i)
              hash = (hash << 5) - hash + char
              hash = hash & hash
            }
            return hash.toString(36)
          }

          // Serialize config for sharing
          // Use validated config (not raw body) — strip 'version' since serializeAdditionConfig adds it
          const { version: _v, ...configWithoutVersion } = config
          const configJson = serializeAdditionConfig(
            configWithoutVersion as Omit<AdditionConfigV4, 'version'>
          )

          // Create share record
          await db.insert(worksheetShares).values({
            id: shareId,
            worksheetType: 'addition',
            config: configJson,
            createdAt: new Date(),
            views: 0,
            creatorIp: hashIp(ip),
            title: config.name || null,
          })

          // Build full URL
          const protocol = request.headers.get('x-forwarded-proto') || 'https'
          const host = request.headers.get('host') || 'abaci.one'
          shareUrl = `${protocol}://${host}/worksheets/shared/${shareId}`
        }
      } catch (shareError) {
        console.error('Error creating share for QR code:', shareError)
        // Continue without QR code rather than failing the entire request
      }
    }

    // Generate Typst sources (one per page)
    const typstSources = await generateTypstSource(config, problems, shareUrl)

    // Join pages with pagebreak for PDF
    const typstSource = typstSources.join('\n\n#pagebreak()\n\n')

    // Compile with Typst: stdin → stdout
    let pdfBuffer: Buffer
    try {
      pdfBuffer = execSync('typst compile --format pdf - -', {
        input: typstSource,
        maxBuffer: 10 * 1024 * 1024, // 10MB limit
      })
    } catch (error) {
      console.error('Typst compilation error:', error)
      if (error instanceof Error) {
        recordError(error)
      }

      // Extract the actual Typst error message
      const stderr =
        error instanceof Error && 'stderr' in error
          ? String((error as any).stderr)
          : 'Unknown compilation error'

      const traceId = getCurrentTraceId()
      return NextResponse.json(
        {
          error: 'Failed to compile worksheet PDF',
          details: stderr,
          ...(traceId && { traceId }),
          ...(process.env.NODE_ENV === 'development' && {
            typstSource: typstSource.split('\n').slice(0, 20).join('\n') + '\n...',
          }),
        },
        { status: 500 }
      )
    }

    // Track worksheet metrics
    const duration = (Date.now() - startTime) / 1000
    const digits = `${config.digitRange.min}-${config.digitRange.max}`
    metrics.worksheet.generationsTotal.inc({ operator: config.operator, digits, format: 'pdf' })
    metrics.worksheet.generationDuration.observe(
      { operator: config.operator, format: 'pdf' },
      duration
    )
    metrics.worksheet.problemsGenerated.inc({ operator: config.operator }, problems.length)

    // Return binary PDF directly
    return new Response(pdfBuffer as unknown as BodyInit, {
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': `attachment; filename="addition-worksheet-${Date.now()}.pdf"`,
      },
    })
  } catch (error) {
    console.error('Error generating worksheet:', error)
    if (error instanceof Error) {
      recordError(error)
    }

    const errorMessage = error instanceof Error ? error.message : String(error)
    const errorStack = error instanceof Error ? error.stack : undefined
    const traceId = getCurrentTraceId()

    return NextResponse.json(
      {
        error: 'Failed to generate worksheet',
        message: errorMessage,
        ...(traceId && { traceId }),
        ...(process.env.NODE_ENV === 'development' && { stack: errorStack }),
      },
      { status: 500 }
    )
  }
})